4.9.1 Reflection
Java is a safely typed language, in that the result of any expression
is well-defined either as a value of a known type, or a known
exception. Most of the programming you will do in Java should use the
type system, since compilation errors will save you much heartache in
debugging systems at runtime.
However, there are application areas which require the type of objects
to be examinable in detail, such as IDEs and remote method
invocation. To support these sorts of applications, Java provides
reflection, where the class of an object can be determined at runtime,
and this class can be examined to determine which methods are
available, and even invoke these methods with dynamically created
arguments.
The key to reflection is the java.lang.Class, which allows much
information to be determined about a class. This leads onto the other
reflection classes such as java.lang.reflect.Method.
- Determine the class of an object.
- Get information about a class's modifiers, fields, methods, constructors, and superclasses.
- Find out what constants and method declarations belong to an interface.
- Create an instance of a class whose name is not known until runtime.
- Get and set the value of an object's field, even if the field name is unknown to your program until runtime.
- Invoke a method on an object, even if the method is not known until runtime.
- Create a new array, whose size and component type are not known
until runtime, and then modify the array's components.
For more detailed information, try the reflection
tutorial.
Ian Wakeman
2005-02-22