home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

Book Home Java Enterprise in a Nutshell Search this book

Chapter 14. The java.lang.reflect Package

The java.lang.reflect package contains the classes and interfaces that, along with java.lang.Class, comprise the Java Reflection API. This package is new as of Java 1.1. Figure 14-1 shows the class hierarchy.

The Constructor, Field, and Method classes represent the constructors, fields, and methods of a class. Because these types all represent members of a class, they each implement the Member interface, which defines a simple set of methods that can be invoked for any class member. These classes allow information about the class members to be obtained, methods and constructors to be invoked, and fields to be queried and set.

Class member modifiers are represented as integers that specify a number of bit flags. The Modifer class defines static methods that help interpret the meanings of these flags. The Array class defines static methods for creating arrays, and reading and writing array elements.

In Java 1.3, the Proxy class allows the dynamic creation of new Java classes that implement a specified set of interfaces. When an interface method is invoked on an instance of such a proxy class, the invocation is delegated to an InvocationHandler object.

figure

Figure 14-1. The java.lang.reflect package

AccessibleObjectJava 1.2
java.lang.reflect

This class is the superclass of the Method, Constructor, and Field classes; its methods provide a mechanism for trusted applications to work with private, protected, and default visibility members that would otherwise not be accessible through the Reflection API. This class is new as of Java 1.2; in Java 1.1, the Method, Constructor, and Field classes extended Object directly.

To use the java.lang.reflect package to access a member to which your code would not normally have access, pass true to the setAccessible() method. If your code has an appropriate ReflectPermission ("suppressAccessChecks"), this allows access to the member as if it were declared public. The static version of setAccessible() is a convenience method that sets the accessible flag for an array of members, but performs only a single security check.

public class AccessibleObject {
// Protected Constructors
protected AccessibleObject ();
// Public Class Methods
public static void setAccessible (AccessibleObject[ ] array, boolean flag) throws SecurityException;
// Public Instance Methods
public boolean isAccessible ();
public void setAccessible (boolean flag) throws SecurityException;
}

Subclasses: Constructor, Field, Method

Passed To: AccessibleObject.setAccessible()

ArrayJava 1.1
java.lang.reflectPJ1.1

This class contains methods that allow you to set and query the values of array elements, to determine the length of an array, and to create new instances of arrays. Note that the Array class can manipulate only array values, not array types; Java data types, including array types, are represented by java.lang.Class. Since the Array class represents a Java value, unlike the Field, Method, and Constructor classes, which represent class members, the Array class is significantly different (despite some surface similarities) from those other classes in this package. Most notably, all the methods of Array are static and apply to all array values, not just a specific field, method, or constructor.

The get() method returns the value of the specified element of the specified array as an Object. If the array elements are of a primitive type, the value is converted to a wrapper object before being returned. You can also use getInt() and related methods to query array elements and return them as specific primitive types. The set() method and its primitive type variants perform the opposite operation. Also, the getLength() method returns the length of the array.

The newInstance() methods create new arrays. One version of this method is passed the number of elements in the array and the type of those elements. The other version of this method creates multidimensional arrays. Besides specifying the component type of the array, it is passed an array of numbers. The length of this array specifies the number of dimensions for the array to be created, and the values of each of the array elements specify the size of each dimension of the created array.

public final class Array {
// No Constructor
// Public Class Methods
public static Object get (Object array, int index) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static boolean getBoolean (Object array, int index) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static byte getByte (Object array, int index) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static char getChar (Object array, int index) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static double getDouble (Object array, int index) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static float getFloat (Object array, int index) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static int getInt (Object array, int index) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static int getLength (Object array) throws IllegalArgumentException; native
public static long getLong (Object array, int index) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static short getShort (Object array, int index) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static Object newInstance (Class componentType, int length) throws NegativeArraySizeException;
public static Object newInstance (Class componentType, int[ ] dimensions) throws IllegalArgumentExceptionNegativeArraySizeException;
public static void set (Object array, int index, Object value) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static void setBoolean (Object array, int index, boolean z) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static void setByte (Object array, int index, byte b) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static void setChar (Object array, int index, char c) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static void setDouble (Object array, int index, double d) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static void setFloat (Object array, int index, float f) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static void setInt (Object array, int index, int i) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static void setLong (Object array, int index, long l) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
public static void setShort (Object array, int index, short s) throws IllegalArgumentExceptionArrayIndexOutOfBoundsException; native
}
ConstructorJava 1.1
java.lang.reflectPJ1.1

This class represents a constructor method of a class. Instances of Constructor are obtained by calling getConstructor() and related methods of java.lang.Class. Constructor implements the Member interface, so you can use the methods of that interface to obtain the constructor name, modifiers, and declaring class. In addition, getParameterTypes() and getExceptionTypes() also return important information about the represented constructor.

In addition to these methods that return information about the constructor, the newInstance() method allows the constructor to be invoked with an array of arguments in order to create a new instance of the class that declares the constructor. If any of the arguments to the constructor are of primitive types, they must be converted to their corresponding wrapper object types to be passed to newInstance(). If the constructor causes an exception, the Throwable object it throws is wrapped within the InvocationTargetException that is thrown by newInstance(). Note that newInstance() is much more useful than the newInstance() method of java.lang.Class because it can pass arguments to the constructor.

public final class Constructor extends AccessibleObject implements Member {
// No Constructor
// Public Instance Methods
public Class[ ] getExceptionTypes ();
public Class[ ] getParameterTypes ();
public Object newInstance (Object[ ] initargs) throws InstantiationExceptionIllegalAccessExceptionIllegalArgumentExceptionInvocationTargetException; native
// Methods Implementing Member
public Class getDeclaringClass ();
public int getModifiers ();
public String getName ();
// Public Methods Overriding Object
public boolean equals (Object obj);
public int hashCode ();
public String toString ();
}

Hierarchy: Object-->AccessibleObject-->Constructor(Member)

Returned By: Class.{getConstructor(), getConstructors(), getDeclaredConstructor(), getDeclaredConstructors()}

FieldJava 1.1
java.lang.reflectPJ1.1

This class represents a field of a class. Instances of Field are obtained by calling the getField() and related methods of java.lang.Class. Field implements the Member interface, so once you have obtained a Field object, you can use getName(), getModifiers(), and getDeclaringClass() to determine the name, modifiers, and class of the field. Additionally, getType() returns the type of the field.

The set() method sets the value of the represented field for a specified object. (If the represented field is static, no object need be specified, of course.) If the field is of a primitive type, its value can be specified using a wrapper object of type Boolean, Integer, and so on, or it can be set using the setBoolean(), setInt(), and related methods. Similarly, the get() method queries the value of the represented field for a specified object and returns the field value as an Object. Various other methods query the field value and return it as various primitive types.

public final class Field extends AccessibleObject implements Member {
// No Constructor
// Public Instance Methods
public Object get (Object obj) throws IllegalArgumentExceptionIllegalAccessException; native
public boolean getBoolean (Object obj) throws IllegalArgumentExceptionIllegalAccessException; native
public byte getByte (Object obj) throws IllegalArgumentExceptionIllegalAccessException; native
public char getChar (Object obj) throws IllegalArgumentExceptionIllegalAccessException; native
public double getDouble (Object obj) throws IllegalArgumentExceptionIllegalAccessException; native
public float getFloat (Object obj) throws IllegalArgumentExceptionIllegalAccessException; native
public int getInt (Object obj) throws IllegalArgumentExceptionIllegalAccessException; native
public long getLong (Object obj) throws IllegalArgumentExceptionIllegalAccessException; native
public short getShort (Object obj) throws IllegalArgumentExceptionIllegalAccessException; native
public Class getType ();
public void set (Object obj, Object value) throws IllegalArgumentExceptionIllegalAccessException; native
public void setBoolean (Object obj, boolean z) throws IllegalArgumentExceptionIllegalAccessException; native
public void setByte (Object obj, byte b) throws IllegalArgumentExceptionIllegalAccessException; native
public void setChar (Object obj, char c) throws IllegalArgumentExceptionIllegalAccessException; native
public void setDouble (Object obj, double d) throws IllegalArgumentExceptionIllegalAccessException; native
public void setFloat (Object obj, float f) throws IllegalArgumentExceptionIllegalAccessException; native
public void setInt (Object obj, int i) throws IllegalArgumentExceptionIllegalAccessException; native
public void setLong (Object obj, long l) throws IllegalArgumentExceptionIllegalAccessException; native
public void setShort (Object obj, short s) throws IllegalArgumentExceptionIllegalAccessException; native
// Methods Implementing Member
public Class getDeclaringClass ();
public int getModifiers ();
public String getName ();
// Public Methods Overriding Object
public boolean equals (Object obj);
public int hashCode ();
public String toString ();
}

Hierarchy: Object-->AccessibleObject-->Field(Member)

Passed To: javax.ejb.deployment.EntityDescriptor.setContainerManagedFields()

Returned By: Class.{getDeclaredField(), getDeclaredFields(), getField(), getFields()}, javax.ejb.deployment.EntityDescriptor.getContainerManagedFields()

InvocationHandlerJava 1.3 Beta
java.lang.reflect

This interface defines a single invoke() method that is called whenever a method is invoked on a dynamically created Proxy object. Every Proxy object has an associated InvocationHandler object that is specified when the Proxy is instantiated. All method invocations on the proxy object are translated into calls to the invoke() method of the InvocationHandler.

The first argument to invoke() is the Proxy object through which the method was invoked. The second argument is a Method object that represents the method that was invoked. Call the getDeclaringClass() method of this Method object to determine the interface in which the method was declared. This may be a superinterface of one of the specified interfaces or even java.lang.Object when the method invoked is toString(), hashCode(), or one of the other Object methods. The third argument to invoke() is the array of method arguments. Any primitive type arguments are wrapped in their corresponding object wrappers (e.g., Boolean, Integer, Double).

The value returned by invoke() becomes the return value of the proxy object method invocation and must be of an appropriate type. If the proxy object method returns a primitive type, invoke() should return an instance of the corresponding wrapper class. invoke() can throw any unchecked (i.e., runtime) exceptions or any checked exceptions declared by the proxy object method. If invoke() throws a checked exception that is not declared by the proxy object, that exception is wrapped within an unchecked UndeclaredThrowableException that is thrown in its place.

public interface InvocationHandler {
// Public Instance Methods
public abstract Object invoke (Object proxy, Method method, Object[ ] args) throws Throwable;
}

Passed To: Proxy.{newProxyInstance(), Proxy()}

Returned By: Proxy.getInvocationHandler()

Type Of: Proxy.h

InvocationTargetExceptionJava 1.1
java.lang.reflectserializable checked PJ1.1

An object of this class is thrown by Method.invoke() and Constructor.newInstance() when an exception is thrown by the method or constructor invoked through those methods. The InvocationTargetException class serves as a wrapper around the object that was thrown; that object can be retrieved with the getTargetException() method.

public class InvocationTargetException extends Exception {
// Public Constructors
public InvocationTargetException (Throwable target);
public InvocationTargetException (Throwable target, String s);
// Protected Constructors
protected InvocationTargetException ();
// Public Instance Methods
public Throwable getTargetException ();
// Public Methods Overriding Throwable
1.2public void printStackTrace ();
1.2public void printStackTrace (java.io.PrintWriter pw);
1.2public void printStackTrace (java.io.PrintStream ps);
}

Hierarchy: Object-->Throwable(Serializable)-->Exception-->InvocationTargetException

Thrown By: java.awt.EventQueue.invokeAndWait(), Constructor.newInstance(), Method.invoke(), javax.swing.SwingUtilities.invokeAndWait()

MemberJava 1.1
java.lang.reflectPJ1.1

This interface defines the methods shared by all members (fields, methods, and constructors) of a class. getName() returns the name of the member, getModifiers() returns its modifiers, and getDeclaringClass() returns the Class object that represents the class of which the member is a part.

public interface Member {
// Public Constants
public static final int DECLARED ; =1
public static final int PUBLIC ; =0
// Public Instance Methods
public abstract Class getDeclaringClass ();
public abstract int getModifiers ();
public abstract String getName ();
}

Implementations: Constructor, Field, Method

MethodJava 1.1
java.lang.reflectPJ1.1

This class represents a method. Instances of Method are obtained by calling the getMethod() and related methods of java.lang.Class. Method implements the Member interface, so you can use the methods of that interface to obtain the method name, modifiers, and declaring class. In addition, getReturnType(), getParameterTypes(), and getExceptionTypes() also return important information about the represented method.

Perhaps most importantly, the invoke() method allows the method represented by the Method object to be invoked with a specified array of argument values. If any of the arguments are of primitive types, they must be converted to their corresponding wrapper object types in order to be passed to invoke(). If the represented method is an instance method (i.e., if it is not static), the instance on which it should be invoked must also be passed to invoke(). The return value of the represented method is returned by invoke(). If the return value is a primitive value, it is first converted to the corresponding wrapper type. If the invoked method causes an exception, the Throwable object it throws is wrapped within the InvocationTargetException that is thrown by invoke().

public final class Method extends AccessibleObject implements Member {
// No Constructor
// Property Accessor Methods (by property name)
public Class getDeclaringClass (); Implements:Member
public Class[ ] getExceptionTypes ();
public int getModifiers (); Implements:Member
public String getName (); Implements:Member
public Class[ ] getParameterTypes ();
public Class getReturnType ();
// Public Instance Methods
public Object invoke (Object obj, Object[ ] args) throws IllegalAccessExceptionIllegalArgumentExceptionInvocationTargetException; native
// Methods Implementing Member
public Class getDeclaringClass ();
public int getModifiers ();
public String getName ();
// Public Methods Overriding Object
public boolean equals (Object obj);
public int hashCode ();
public String toString ();
}

Hierarchy: Object-->AccessibleObject-->Method(Member)

Passed To: Too many methods to list.

Returned By: java.beans.EventSetDescriptor.{getAddListenerMethod(), getListenerMethods(), getRemoveListenerMethod()}, java.beans.IndexedPropertyDescriptor.{getIndexedReadMethod(), getIndexedWriteMethod()}, java.beans.MethodDescriptor.getMethod(), java.beans.PropertyDescriptor.{getReadMethod(), getWriteMethod()}, Class.{getDeclaredMethod(), getDeclaredMethods(), getMethod(), getMethods()}, javax.ejb.deployment.AccessControlEntry.getMethod(), javax.ejb.deployment.ControlDescriptor.getMethod()

ModifierJava 1.1
java.lang.reflectPJ1.1

This class defines a number of constants and static methods that can interpret the integer values returned by the getModifiers() methods of the Field, Method, and Constructor classes. The isPublic(), isAbstract(), and related methods return true if the modifier value includes the specified modifier; otherwise, they return false. The constants defined by this class specify the various bit flags used in the modifiers value. You can use these constants to test for modifiers if you want to perform your own boolean algebra.

public class Modifier {
// Public Constructors
public Modifier ();
// Public Constants
public static final int ABSTRACT ; =1024
public static final int FINAL ; =16
public static final int INTERFACE ; =512
public static final int NATIVE ; =256
public static final int PRIVATE ; =2
public static final int PROTECTED ; =4
public static final int PUBLIC ; =1
public static final int STATIC ; =8
1.2public static final int STRICT ; =2048
public static final int SYNCHRONIZED ; =32
public static final int TRANSIENT ; =128
public static final int VOLATILE ; =64
// Public Class Methods
public static boolean isAbstract (int mod);
public static boolean isFinal (int mod);
public static boolean isInterface (int mod);
public static boolean isNative (int mod);
public static boolean isPrivate (int mod);
public static boolean isProtected (int mod);
public static boolean isPublic (int mod);
public static boolean isStatic (int mod);
1.2public static boolean isStrict (int mod);
public static boolean isSynchronized (int mod);
public static boolean isTransient (int mod);
public static boolean isVolatile (int mod);
public static String toString (int mod);
}
ProxyJava 1.3 Beta
java.lang.reflectserializable

This class defines a simple but powerful API for dynamically generating a proxy class. A proxy class implements a specified list of interfaces and delegates invocations of the methods defined by those interfaces to a separate invocation handler object.

The static getProxyClass() method dynamically creates a new Class object that implements each of the interfaces specified in the supplied Class[] array. The newly created class is defined in the context of the specified ClassLoader. The Class returned by getProxyClass() is a subclass of Proxy. Every class that is dynamically generated by getProxyClass() has a single public constructor, which expects a single argument of type InvocationHandler. You can create an instance of the dynamic proxy class by using the Constructor class to invoke this constructor. Or, more simply, you can combine the call to getProxyClass() with the constructor call by calling the static newProxyInstance() method, which both defines and instantiates a proxy class.

Every instance of a dynamic proxy class has an associated InvocationHandler object. All method calls made on a proxy class are translated into calls to the invoke() method of this InvocationHandler object, which can handle the call in any way it sees fit. The static getInvocationHandler() method returns the InvocationHandler object for a given proxy object. The static isProxyClass() method returns true if a specified Class object is a dynamically generated proxy class.

public class Proxy implements Serializable {
// Protected Constructors
protected Proxy (InvocationHandler h);
// Public Class Methods
public static InvocationHandler getInvocationHandler (Object proxy) throws IllegalArgumentException;
public static Class getProxyClass (ClassLoader loader, Class[ ] interfaces) throws IllegalArgumentException;
public static boolean isProxyClass (Class cl);
public static Object newProxyInstance (ClassLoader loader, Class[ ] interfaces, InvocationHandler h) throws IllegalArgumentException;
// Protected Instance Fields
protected InvocationHandler h ;
}

Hierarchy: Object-->Proxy(Serializable)

ReflectPermissionJava 1.2
java.lang.reflectserializable permission

This class is a java.security.Permission that governs access to private, protected, and default-visibility methods, constructors, and fields through the Java Reflection API. In Java 1.2, the only defined name, or target, for ReflectPermission is "suppressAccessChecks". This permission is required to call the setAccessible() method of AccessibleObject. Unlike some Permission subclasses, ReflectPermission does not use a list of actions. See also AccessibleObject.

System administrators configuring security policies should be familiar with this class, but application programmers should never need to use it directly.

public final class ReflectPermission extends java.security.BasicPermission {
// Public Constructors
public ReflectPermission (String name);
public ReflectPermission (String name, String actions);
}

Hierarchy: Object-->java.security.Permission(java.security.Guard,Serializable)-->java.security.BasicPermission(Serializable)-->ReflectPermission

UndeclaredThrowableExceptionJava 1.3 Beta
java.lang.reflectserializable unchecked

Thrown by a method of a Proxy object if the invoke() method of the proxy's InvocationHandler throws a checked exception not declared by the original method. This class serves as an unchecked exception wrapper around the checked exception. Use getUndeclaredThrowable() to obtain the checked exception thrown by invoke().

public class UndeclaredThrowableException extends RuntimeException {
// Public Constructors
public UndeclaredThrowableException (Throwable undeclaredThrowable);
public UndeclaredThrowableException (Throwable undeclaredThrowable, String s);
// Public Instance Methods
public Throwable getUndeclaredThrowable ();
// Public Methods Overriding Throwable
public void printStackTrace ();
public void printStackTrace (java.io.PrintStream ps);
public void printStackTrace (java.io.PrintWriter pw);
}

Hierarchy: Object-->Throwable(Serializable)-->Exception-->RuntimeException-->UndeclaredThrowableException



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.







??????????????@Mail.ru