Java Reference
In-Depth Information
cons[1] = int.class;
Constructor c = kc.getConstructor(cons);
The getConstructor( Class[] ) method throws a NoSuchMethodException if there isn't
a constructor with arguments that match the Class[] array.
After you have a Constructor object, you can call its newInstance( Object[] ) method
to create a new instance using that constructor.
Inspecting a Class
To bring all this material together, Listing 16.3 is a short Java application named
MethodInspector that uses reflection to inspect the methods in a class.
16
LISTING 16.3
The Full Text of MethodInspector.java
1: import java.lang.reflect.*;
2:
3: public class MethodInspector {
4: public static void main(String[] arguments) {
5: Class inspect;
6: try {
7: if (arguments.length > 0)
8: inspect = Class.forName(arguments[0]);
9: else
10: inspect = Class.forName(“MethodInspector”);
11: Method[] methods = inspect.getDeclaredMethods();
12: for (int i = 0; i < methods.length; i++) {
13: Method methVal = methods[i];
14: Class returnVal = methVal.getReturnType();
15: int mods = methVal.getModifiers();
16: String modVal = Modifier.toString(mods);
17: Class[] paramVal = methVal.getParameterTypes();
18: StringBuffer params = new StringBuffer();
19: for (int j = 0; j < paramVal.length; j++) {
20: if (j > 0)
21: params.append(“, “);
22: params.append(paramVal[j].getName());
23: }
24: System.out.println(“Method: “ + methVal.getName() + “()”);
25: System.out.println(“Modifiers: “ + modVal);
26: System.out.println(“Return Type: “ + returnVal.getName());
27: System.out.println(“Parameters: “ + params + “\n”);
28: }
29: } catch (ClassNotFoundException c) {
30: System.out.println(c.toString());
31: }
32: }
33: }
 
Search WWH ::




Custom Search