Java Reference
In-Depth Information
Chapter 16. Reflection
A sense of humor keen enough to show a man his own absurdities
will keep him from the commission of all sins, or nearly all, save
those that are worth committing.
Samuel Butler
The package java.lang.reflect contains the reflection package, the
classes you can use to examine a type in detail. You can write a complete
type browser using these classes, or you can write an application that
interprets code that a user writes, turning that code into actual uses of
classes, creation of objects, invocations of methods, and so on. Almost
all the types mentioned in this discussion on reflection are contained in
the package java.lang.reflect , except for the classes Class and Package ,
which are part of the package java.lang , and Annotation , which is part of
the java.lang.annotation package.
Reflection starts with a Class object. From the Class object you can obtain
a complete list of members of the class, find out all the types of the class
(the interfaces it implements, the classes it extends), and find out in-
formation about the class itself, such as the modifiers applied to it ( pub-
lic , abstract , final , and so on) or the package it is contained in. Reflec-
tion is also sometimes called introspection; both terms use the metaphor
of asking the type to look at itself and tell you something. These cap-
abilities can be used by type browsers to show the structure of an ap-
plication. They also form the first step for you to dynamically create and
manipulate objects.
Here's a simple example of a "type browser." Given the name of a class
this program shows the class's immediate superclass and lists all the
public methods it declares:
import java.lang.reflect.*;
import static java.lang.System.out;
import static java.lang.System.err;
 
Search WWH ::




Custom Search