Previous | Next | Trail Map | The Reflection API | Contents

The Reflection API

by Dale Green

The reflection API represents, or reflects, the classes, interfaces, and objects in the current Java Virtual Machine. You'll want to use the reflection API if you are writing development tools such as debuggers, class browsers, and GUI builders. With the reflection API you can:

First, a note of caution. Don't use the reflection API when other tools more natural to the Java programming language would suffice. For example, if you are in the habit of using function pointers in another language, you might be tempted to use the Method objects of the reflection API in the same way. Resist the temptation! In this case, your program will be easier to debug and maintain if you don't use Method objects. Instead, you should define an interface, and then implement the interface in the classes that perform the needed action.

Other trails in the tutorial use the term "member variable" instead of "field." The two terms are synonymous. Because the Field class is part of of the reflection API, this trail uses the term "field."

This trail employs a task-oriented approach to the reflection API. Each lesson includes a set of related tasks, and every task is explained, step-by-step, with a sample program. The lessons are as follows:

Examining Classes explains how to determine the class of an object, and how to get information about classes and interfaces.

Manipulating Objects shows you how to instantiate classes, get or set field values, and invoke methods. With the reflection API, you can perform these tasks even if the names of the classes, fields, and methods are unknown until run time.

Working with Arrays describes the APIs used to create and modify arrays whose names are not known until run time.

Summary of Classes lists the classes that comprise the reflection API, and provides links to the apppropriate API documentation.


Note: Many of the APIs documented in this trail were added to the Java Development Kit (JDK) for its 1.1 release. Therefore, the code examples in this trail will work only on Java platforms that are compatible with the JDK software releases 1.1.

Please send comments about this trail to: tutorial@java.sun.com. In your message, place reflection in the subject header. Your feedback is important to us!


Previous | Next | Trail Map | The Reflection API | Contents