O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required