Printing Class Information
Problem
You want to print all the information about a class, similar to the way javap does.
Solution
Get a Class object, call its getFields( )
and
getMethods( ), and print the results.
Discussion
The JDK includes a program called javap , the Java Printer. Sun’s JDK version normally prints the outline of a class file -- a list of its methods and fields -- but can also print out the Java bytecodes or machine instructions. The Kaffe package did not include a version of javap, so I wrote one and contributed it (see Example 25-8). The Kaffe folk have expanded it somewhat, but it still works basically the same. My version doesn’t print the bytecodes; it behaves rather like Sun’s behaves when you don’t give theirs any command-line options.
The getFields( ) and getMethods( ) methods
return array of Field
and Method respectively; these are both in package
java.lang.reflect. I use a
Modifiers object to get details on the
permissions and storage
attributes of the fields and methods. In many implementations you can
bypass this, and simply call toString( )
in
each Field and Method object.
Doing it this way gives me a bit more control over the
formatting.
Example 25-8. MyJavaP.java
import java.io.*; import java.util.*; import java.lang.reflect.*; /** * JavaP prints structural information about classes. * For each class, all public fields and methods are listed. * "Reflectance" is used to look up the information. */ public class MyJavaP { /** A "Modifier" object, ...