Java Reference
In-Depth Information
Each of these reflection classes has methods for working with an element of a class.
A Method object holds information about a single method in a class. To find out about
all methods contained in a class, create a Class object for that class and call
getDeclaredMethods() on that object. An array of Method[] objects is returned that rep-
resents all methods in the class not inherited from a superclass. If no methods meet that
description, the length of the array is 0.
The Method class has several useful instance methods:
getParameterTypes() —This method returns an array of Class objects represent-
ing each argument contained in the method signature.
n
getReturnType() —This method returns a Class object representing the return
type of the method, whether it's a class or primitive type.
n
getModifiers() —This method returns an int value that represents the modifiers
that apply to the method, such as whether it is public , private , and the like.
n
Because the getParameterTypes() and getReturnType() methods return Class objects,
you can use getName() on each object to find out more about it.
The easiest way to use the int returned by getModifiers() is to call the Modifier class
method toString() with that integer as an argument. For example, if you have a Method
object named current , you can display its modifiers with the following code:
int mods = current.getModifiers();
System.out.println(Modifier.toString(mods));
The Constructor class has some of the same methods as the Method class, including
getModifiers() and getName() . One method that's missing, as you might expect, is
getReturnType() ; constructors do not contain return types.
To retrieve all constructors associated with a Class object, call getConstructors() on
that object. An array of Constructor objects is returned.
To retrieve a specific constructor, first create an array of Class objects that represent
every argument sent to the constructor. When this is done, call getConstructors() with
that Class array as an argument.
For example, if there is a KeyClass( String , int ) constructor, you can create a
Constructor object to represent this with the following statements:
Class kc = KeyClass.class;
Class[] cons = new Class[2];
cons[0] = String.class;
Search WWH ::




Custom Search