Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
several methods that can be used to obtain information about an object. You will want to
explore these on your own. However, each supports thetoString( )method. Therefore,
usingConstructor,Field, andMethodobjects as arguments to theprintln( )method is
straightforward, as shown in the program.

// Demonstrate reflection.
import java.lang.reflect.*;
public class ReflectionDemo1 {
public static void main(String args[]) {
try {
Class c = Class.forName("java.awt.Dimension");
System.out.println("Constructors:");
Constructor constructors[] = c.getConstructors();
for(int i = 0; i < constructors.length; i++) {
System.out.println(" " + constructors[i]);
}

System.out.println("Fields:");
Field fields[] = c.getFields();
for(int i = 0; i < fields.length; i++) {
System.out.println(" " + fields[i]);
}

System.out.println("Methods:");
Method methods[] = c.getMethods();
for(int i = 0; i < methods.length; i++) {
System.out.println(" " + methods[i]);
}
}
catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}

834 Part II: The Java Library


Class Primary Function
AccessibleObject Allows you to bypass the default access control checks.
Array Allows you to dynamically create and manipulate arrays.
Constructor Provides information about a constructor.
Field Provides information about a field.
Method Provides information about a method.
Modifier Provides information about class and member access modifiers.
Proxy Supports dynamic proxy classes.
ReflectPermission Allows reflection of private or protected members of a class.

TABLE 27-4 Classes Defined injava.lang.reflect
Free download pdf