Reflection: A New Way to Discover Information about Java classes
By Dan Becker2003-05-24
Outlining the Class Hierarchy Using Java 1.02
At the simplest level, Java allows programs to inspect class information through the Java class named Class, located in the package java.lang. The most important methods are getName() and getSuperclass(), which allow you to print the name of the class and find the super class (or parent) of the given class.
Let's begin by expanding on an example given by the grandfathers of the Java Language, Ken Arnold and James Gosling, in the book The Java Programming Language . The Java application shown below creates an instance of itself and calls the printType(...) method for each command line argument.
In this example, the printType method encapsulates all the reflection code. It prints the name of the class, via the getName() method, and recursively calls itself on its super class, via the getSuperclass() method. This example is the simplest form of reflection and was supported in Java 1.01 and 1.02. Notice that we don't have to import the reflection package because the Java class Class and its methods are located in the java.lang package.
|
When you compile and run this program, you should see output similar to the output shown below.
|
The name of the given class is followed by all of its parent classes, ending with the mother of all Java classes, java.lang.Object. Note that the output reflects the fully qualified class name of java.lang.Integer since all Java class names are stored with their scope. There is no notion of package importing in the Java run time.
If you do not get similar results, check your code and your Java environment. Make any appropriate changes to product-similar results, or the rest of the examples in this article will also fail.
Tutorial Pages:
» Introduction
» Outlining the Class Hierarchy Using Java 1.02
» Querying Interfaces Using Java 1.02
» An Improved Java 1.02 Reflection Program
» Using the Reflection Features of Java 1.1: Modifiers
» Using the Reflection Features of Java 1.1: Fields
» Security Issues
» Conclusion
First published by IBM DeveloperWorks
