Discovering Method Information


Class c = someObject.getClass(); Method[] methods = c.getMethods(); for (int i = 0; i < methods.length; i++) {    String methodName = methods[i].getName();    System.out.println("Name: " + methodName);    String returnType =       methods[i].getReturnType().getName();    System.out.println("Return Type: " + returnType);    Class[] paramTypes =       methods[i].getParameterTypes();    System.out.print("Parameter Types:");    for (int k = 0; k < paramTypes.length; k ++) {       String paramTypeStr = paramTypes[k].getName();       System.out.print(" " + paramTypeStr);    }    System.out.println(); }



You can get information about a class's public methods by calling the getMethods() method on a Class object. This method returns an array of Method objects. Using the Method object, you can then get the method's name, return type, parameter types, modifiers, and throwable exceptions. You can also use the Method.invoke() method to call the method. For more information about invoking methods, see the "Invoking Methods" phrase also in this chapter.

In this phrase, after getting the array of methods, we print the method name, the method's return type, and a list of the method's parameter types.

You can also get an individual public method instead of all the methods of an object if you know the method's name and parameter types. The following example shows how you would get an individual method:

Class c = someObject.getClass(); Class[] paramTypes =    new Class[] {String.class, Integer.class}; Method meth = c.getMethod("setValues", paramTypes);


In this example, we get a Method object representing the method with the name setValue and taking two parameters, a String and an Integer.

The methods we've discussed so far, getMethods() and getMethod(), return all the public methods that can be access through the class. Corresponding methods are available to get all methods regardless of their access type. The methods getdeclaredMethods() and getdeclaredMethod() behave exactly like their counterparts, except that they return all the class's methods, regardless of access type. This allows you to get even private methods.

Often an Integrated Development Environment (IDE) such as Eclipse will include a class browser as a feature. The class browser allows the developer to visually navigate through a hierarchy of classes. This technique is one of the ways in which class browsers are constructed. In order to build a visual class browser, your application must have a way of knowing all the methods of any given class.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net