The first form finds a public field that is either declared or inherited, while the second finds only a declared
field that need not be public. If the named field does not exist, a NoSuchFieldException is thrown. Note
that the implicit length field of an array is not returned when these methods are invoked on an array type.
Particular methods are identified by their signaturetheir name and a sequence of Class objects representing
the number and type of their parameters. Remember that for a varargs method the last parameter will actually
be an array.
public Method
getMethod(String name, Class... parameterTypes)
public Method
getDeclaredMethod(String name, Class... parameterTypes)
Similarly, constructors are identified by their parameter number and types:
public Constructor
getConstructor(Class... parameterTypes)
public Constructor
getDeclaredConstructor(Class... parameterTypes)
In both cases, if the specified method or constructor does not exist, you will get a
NoSuchMethodException.
Note that when you ask for a single constructor you get a parameterized constructor type,
Constructor
constructors is not parameterized by T. This is because you can't create a generic array. Any constructor
extracted from the array is essentially of an unknown kind, but this only affects use of the invoke method,
which we discuss a little later.
All the above methods require a security check before they can proceed and so will interact with any installed
security managersee "Security" on page 677. If no security manager is installed then all these methods will be
allowed. Typically, security managers will allow any code to invoke methods that request information on the
public members of a typethis enforces the normal language level access rules. However, access to non-public
member information will usually be restricted to privileged code within the system. Note that the only
distinction made is between public and non-public memberssecurity managers do not have enough
information to enforce protected or package-level access. If access is not allowed, a SecurityException
is thrown.
The following program lists the public fields, methods, and constructors of a given class:
import java.lang.reflect.*;
public class ClassContents {
public static void main(String[] args) {
try {
Class<?> c = Class.forName(args[0]);
System.out.println(c);
printMembers(c.getFields());
printMembers(c.getConstructors());
printMembers(c.getMethods());
} catch (ClassNotFoundException e) {
System.out.println("unknown class: " + args[0]);
}
}