Java Reflection
Java looking at Java
One of the unusual capabilities of Java is that a program can examine itself
You can determine the class of an object You can find out all about a class: its access modifiers, superclass, fields, constructors, and methods You can find out what what is in an interface Even if you dont know the names of things when you write the program, you can: Create an instance of a class Get and set instance variables Invoke a method on an object Create and manipulate arrays
I guess this is called reflection because its as if a Java program could look in a mirror at itself
What is reflection for?
In normal programs you dont need reflection You do need reflection if you are working with programs that process programs Typical examples:
A class browser A debugger A GUI builder An IDE, such as BlueJ or Fort A program to grade student programs
The Class class
To find out about a class, first get its Class object
If you have an object obj, you can get its class object with Class c = [Link](); You can get the class object for the superclass of a Class c with Class sup = [Link](); If you know the name of a class (say, Button) at compile time, you can get its class object with Class c = [Link]; If you know the name of a class at run time (in a String variable str), you can get its class object with Class c = [Link](str);
Getting the class name
If you have a class object c, you can get the name of the class with [Link]() getName returns the fully qualified name; that is, Class c = [Link]; String s = [Link](); [Link](s); will print [Link] Class Class and its methods are in [Link], which is always imported and available
Getting all the superclasses
getSuperclass() returns a Class object (or null if you call it on Object, which has no superclass) The following code is from the Sun tutorial: static void printSuperclasses(Object o) { Class subclass = [Link](); Class superclass = [Link](); while (superclass != null) {
String className = [Link](); [Link](className); subclass = superclass; superclass = [Link]();
Getting the class modifiers I
A Class object has an instance method getModifiers() that returns an int To decipher the int result, we need methods of the Modifier class, which is in [Link], so: import [Link].*; Now we can do things like: if ([Link](m)) [Link]("public");
Getting the class modifiers II
Modifier contains these methods (among others):
public public public public public public public static static static static static static static boolean isAbstract(int) boolean isFinal(int) boolean isInterface(int) boolean isPrivate(int) boolean isProtected(int) boolean isPublic(int) String toString(int)
This will return a string such as "public final synchronized strictfp"
Getting interfaces
A class can implement zero or more interfaces getInterfaces() returns an array of Class objects More code from Sun: static void printInterfaceNames(Object o) { Class c = [Link](); Class[] theInterfaces = [Link](); for (int i = 0; i < [Link]; i++) { String interfaceName = theInterfaces[i].getName(); [Link](interfaceName); } } Note that zero-length arrays are perfectly legal in Java
Examining classes and interfaces
The class Class represents both classes and interfaces To determine if a given Class object c is an interface, use [Link]() To find out more about a class object, use:
getModifiers() getFields() // "fields" == "instance variables" getConstructors() getMethods() isArray()
Getting Fields
public Field[] getFields() throws SecurityException Returns an array of public Fields (variables) The length of the array may be zero The fields are not returned in any particular order Both locally defined and inherited instance variables are returned, but not static variables public Field getField(String name) throws NoSuchFieldException, SecurityException Returns the named public Field If no immediate field is found, the superclasses and interfaces are searched recursively
Using Fields, I
If f is a Field object, then
[Link]() returns the simple name of the field [Link]() returns the type (Class) of the field [Link]() returns the Modifiers of the field [Link]() returns a String containing access modifiers, the type, and the fully qualified field name
Example: public [Link] [Link]
[Link]() returns the Class in which this field is declared
Using Fields, II
The fields of a particular object obj may be accessed with:
boolean [Link](obj), int [Link](obj), double [Link](obj), etc., return the value of the field, assuming it is that type or can be widened to that type Object [Link](obj) returns the value of the field, assuming it is an Object void [Link](obj, value), void [Link](obj, bool), void [Link](obj, i), void [Link](obj, d), etc. set the value of a field
Constructors
If c is a Constructor object, then
[Link]() returns the name of the constructor, as a String (this is the same as the name of the class) [Link]() returns the Class in which this constructor is declared [Link]() returns the Modifiers of the constructor [Link]() returns an array of Class objects, in declaration order [Link](Object[] initargs) creates and returns a new instance of class c
Arguments that should be primitives are automatically unwrapped as needed
Methods
public Method[] getMethods() throws SecurityException Returns an array of Method objects These are the public member methods of the class or interface, including inherited methods The methods are returned in no particular order public Method getMethod(String name, Class[] parameterTypes) throws NoSuchMethodException, SecurityException
Method methods, I
getDeclaringClass() Returns the Class object representing the class or interface that declares the method represented by this Method object getName() Returns the name of the method represented by this Method object, as a String getModifiers() Returns the Java language modifiers for the method represented by this Method object, as an integer getParameterTypes() Returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by this Method object
Method methods, II
getReturnType() Returns a Class object that represents the formal return type of the method represented by this Method object toString() Returns a String describing this Method (typically pretty long) public Object invoke(Object obj, Object[] args) Invokes the underlying method represented by this Method object, on the specified object with the specified parameters Individual parameters are automatically unwrapped to match primitive formal parameters
Arrays I
To determine whether an object obj is an array,
Get its class c with Class c = [Link](); Test with [Link]()
To find the type of components of the array,
[Link]() Returns null if c is not the class of an array
There is an Array class in [Link] that provides static methods for working with arrays
Arrays II
To create an array,
[Link](Class componentType, int size) This returns, as an Object, the newly created array
You can cast it to the desired type if you like
The componentType may itself be an array
This would create a multiply-dimensioned array The limit on the number of dimensions is usually 255
[Link](Class componentType, int[] size) This returns, as an Object, the newly created multidimensional array (with [Link] dimensions)
Arrays III
To get the value of array elements,
[Link](Object array, int index) returns an Object [Link](Object array, int index) returns a boolean [Link](Object array, int index) returns a byte etc.
To store values into an array,
[Link](Object array, int index, Object value) [Link](Object array, int index, boolean z) [Link](Object array, int index, byte b) etc.
References
This lecture comes mainly from the following two souces
[Link] ml [Link] [Link] es/ALT/Reflection/
The End