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, to decode modifiers of fields/methods */ Modifier m = new Modifier( ); /** Simple main program, construct self, process each class name * found in argv. */ public static void main(String[] argv) { MyJavaP pp = new MyJavaP( ); if (argv.length == 0) { System.err.println("Usage: javap className [...]"); System.exit(1); } else for (int i=0; i<argv.length; i++) pp.doClass(argv[i]); } /** Format the fields and methods of one class, given its name. */ protected void doClass(String className) { try { Class c = Class.forName(className); System.out.println(m.toString(c.getModifiers( )) + ' ' + c + " {"); int i, mods; Field fields[] = c.getFields( ); for (i = 0; i < fields.length; i++) { if (!m.isPrivate(fields[i].getModifiers( )) && !m.isProtected(fields[i].getModifiers( ))) System.out.println(" " + fields[i]); } Method methods[] = c.getMethods( ); for (i = 0; i < methods.length; i++) { if (!m.isPrivate(methods[i].getModifiers( )) && !m.isProtected(methods[i].getModifiers( ))) System.out.println(" " + methods[i]); } } catch (ClassNotFoundException e) { System.err.println("Error: Class " + className + " not found!"); } catch (Exception e) { System.err.println(e); } finally { System.out.println("}"); } } }
18.191.189.23