Obtaining Class and Member Information
Example 9-1
shows a program that uses the Class
, Constructor
, Field
, and Method
classes to display information about
a specified class. The program’s output is similar to the class
synopses that appear in Java in a Nutshell. (You
might notice that the names of method arguments are not shown;
argument names are not stored in class files, so they are not
available through the Reflection API.)
Here is the output from using ShowClass
on itself:
public class ShowClass extends Object { // Constructors public ShowClass( ); // Fields // Methods public static void main(String[ ]) throws ClassNotFoundException; public static String modifiers(int); public static void print_class(Class); public static String typename(Class); public static void print_field(Field); public static void print_method_or_constructor(Member); }
The code for this example is quite straightforward. It uses the
Class.forName( )
method to
dynamically load the named class, and then calls various methods of
the Class
object to look up the
superclass, interfaces, and members of the class. The example uses
Constructor
, Field
, and Method
objects to obtain information about
each member of the class.
Example 9-1. ShowClass.java
package je3.reflect; import java.lang.reflect.*; /** A program that displays a class synopsis for the named class */ public class ShowClass { /** The main method. Print info about the named class */ public static void main(String[ ] args) throws ClassNotFoundException ...
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.