To find out what methods belong to a class, invoke the method namedgetMethods
. The array returned bygetMethods
containsMethod
objects. You can use aMethod
object to uncover a method's name, return type, parameter types, set of modifiers, and set of throwable exceptions. All of this information would be useful if you were writing a class browser or a debugger. WithMethod.invoke
, you can even call the method itself. To see how to do this, see Invoking Methods. The following sample program prints the name, return type, and parameter types of every public method in thePolygon
class. The program performs these tasks:Not many lines of source code are required to accomplish these tasks:
- It retrieves an array of
Method
objects from theClass
object by callinggetMethods
.- For every element in the
Method
array, the program:
- retrieves the method name by calling
getName
- gets the return type by invoking
getReturnType
- creates an array of
Class
objects by invokinggetParameterTypes
- The array of
Class
objects created in the preceding step represents the parameters of the method. To retrieve the class name for every one of these parameters, the program invokesgetName
against eachClass
object in the array.An abbreviated version of the output generated by the sample program is as follows:import java.lang.reflect.*;
import java.awt.*;
class SampleMethod {
public static void main(String[] args) {
Polygon p = new Polygon();
showMethods(p);
}
static void showMethods(Object o) {
Class c = o.getClass();
Method[] theMethods = c.getMethods();
for (int i = 0; i < theMethods.length; i++) {
String methodString = theMethods[i].getName();
System.out.println("Name: " + methodString);
String returnString =
theMethods[i].getReturnType().getName();
System.out.println(" Return Type: " + returnString);
Class[] parameterTypes = theMethods[i].getParameterTypes();
System.out.print(" Parameter Types:");
for (int k = 0; k < parameterTypes.length; k ++) {
String parameterString = parameterTypes[k].getName();
System.out.print(" " + parameterString);
}
System.out.println();
}
}
}Name: equals
Return Type: boolean
Parameter Types: java.lang.Object
Name: getClass
Return Type: java.lang.Class
Parameter Types:
Name: hashCode
Return Type: int
Parameter Types:
.
.
.
Name: intersects
Return Type: boolean
Parameter Types: double double double double
Name: intersects
Return Type: boolean
Parameter Types: java.awt.geom.Rectangle2D
Name: translate
Return Type: void
Parameter Types: int int
Wednesday, 22 September 2010
Obtaining Method Information
Labels:
java,
Reflection
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment