1. Reflection Basics:
The standard J2SE platform libraries include a reflection API. This API allows classes to reflect on themselves, to see their inner selves. Typically not used by developers, but by tool developers such as those creating an IDE like NetBeans, the reflection API lets you discover the names of classes, methods, and fields. Just finding out the names isn't all you can do though. You can also invoke those methods and access arrays without using square brackets.
The heart of the reflection API is the Class class. This class allows you to find out the name of a class, its access modifiers, fields, methods, and so forth. For any instance of a class, you can get its Class class by calling the getClass method:
Class c = anInstance.getClass();
If you don't happen to have an instance of a class (and don't want to create one), just attach .class to the end of the class name and you have the Class instance for that class.
Class c = MyClass.class;
The same even works for primitives:
Class c = int.class;
This last one might seem odd, but it allows you to specify argument types when calling methods (via Reflection) that accept primitive arguments.
One thing typically done is creating a Class by passing its string name to the forName method of Class.
Class c = Class.forName("java.awt.Button");
This is very common in JDBC technology. This is done so is that so that at compile time you don't have to have the class within the quoted string available. So, if you change JDBC drivers, you won't have to recompile your program if the driver's class name was the quoted string.
Note: When naming the variable for the Class instance, don't name it class. As this is a reserved word, the compiler will think you are trying to define a new class in an inappropriate spot.
Once you have a Class class, that's where the fun begins. You can find out the name of the class with its getName method.
Class c = javax.swing.JButton.class
System.out.println("Name: " + c.getName());
Or, you can find out its superclass with getSuperclass:
System.out.println("Super: " + c.getSuperclass().getName());
[Yields javax.swing.AbstractButton in the case of the JButton.]
Moving from classes to methods takes us to the Method class, found in the java.lang.reflect package. With the Method class, you can discover all methods of a class (with getMethods) and even invoke them (with invoke).
The following program demonstrates getting the methods of a class, where the class name comes from the command line.
import java.lang.reflect.*;
No comments:
Post a Comment