Java Reflection

In this discussion, we consider Java's reflection facilties. Reflection provides Java programs with the capability of getting information about another Java object, such as the name of its class, its methods, the method's arguments and return values, etc. Reflection mechanisms also allow a program to dynamically load a class at run time, create instances of that class, and invoke its methods. Thus, reflection provides meta information and capabilities.


Background

Reflection facilties are found in two packages. The Class class, which is at the core of reflection, is part of the java.lang package. The classes that allow actual inquiries and operations on Class instances are included in the java.lang.reflect package.

You should browse these classes before proceeding.


Examples

In this section, we will look at three cumulative applications. The first specifies a class and asks for its name. The second inquires about all of the methods delcared in the class, along with the return type and argument list for each. The third instantiates the class and invokes several of its methods.

Each of the examples uses a class, called Mystery, as the object of its attention.

Mystery

This class includes String and integer variables. In includes get and set methods for each. It serves as the class of inquiry and operation for the applications that follow.

Name

This application asks the Mystery class for its name and prints the resuslt.

Methods

This application asks the Mystery class for all of the methods declared within it, along with the return value and argument list for each.

Invocation

This application invokes two of the methods in the Mystery class

Update

This application updates the message and integer variables in the Mystery class

Applet

This applet performs the same update operations as the preceding application.


References

References useful for this discussion include the following: