Java Reference
In-Depth Information
CHAPTER 8
Reflection
The Reflection API allows a Java program to inspect and manipulate itself; it com-
prises the java.lang.Class class and the java.lang.reflect package, which rep-
resents the members of a class with Method , Constructor , and Field objects.
Reflection can obtain information about a class and its members. This is the tech-
nique that the JavaBeans (see Chapter 14, JavaBeans ) introspection mechanism
uses to determine the properties, events, and methods that are supported by a
bean, for example. Reflection can also manipulate objects in Java. You can use the
Field class to query and set the values of fields, the Method class to invoke meth-
ods, and the Constructor class to create new objects. The examples in this chap-
ter demonstrate both object inspection and manipulation using the Reflection API.
In addition to the examples in this chapter, the Java Reflection API is also used by
an example in Chapter 17, Database Access with SQL .
Obtaining Class and Member Information
Example 8-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);
 
Search WWH ::




Custom Search