Wednesday 22 September 2010

Obtaining Method Information

To find out what methods belong to a class, invoke the method named getMethods. The array returned by getMethods contains Method objects. You can use a Method 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. With Method.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 the Polygon class. The program performs these tasks:
  1. It retrieves an array of Method objects from the Class object by calling getMethods.
  2. For every element in the Method array, the program:
    1. retrieves the method name by calling getName
    2. gets the return type by invoking getReturnType
    3. creates an array of Class objects by invoking getParameterTypes
  3. 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 invokes getName against each Class object in the array.
Not many lines of source code are required to accomplish these tasks:
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();
}
}
}
An abbreviated version of the output generated by the sample program is as follows:
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

No comments:

Post a Comment