17 e.printStackTrace();
18 } catch (IllegalAccessException e) {
19 e.printStackTrace();
20 }
21 }
如果需要通过调用带有参数的构造函数来创建对象实例,需要使用java.lang.reflect.Constructor对象来完成,见如下代码:
1 public static void main(String args[]) {
2 String className = "java.util.Date";
3 try {
4 Class c2 = Class.forName(className);
5 //找到只接受一个long类型参数的构造器
6 Constructor cc = c2.getConstructor(long.class);
7 long ll = 45L;
8 //将该Constructor期望的指定类型(long)的参数实例传入并构造Date对象。
9 Date dd = (Date)cc.newInstance(ll);
10 System.out.println("Date.toString = " + dd);
11 } catch (Exception e) {
12 e.printStackTrace();
13 }
14 }
3. 遍历一个未知类型的所有域、构造方法和域方法,见如下函数原型:
Field[] getFields(); 返回指定对象域字段数组,主要包含该类及其超类的所有公有(public)域。
Field[] getDeclaredFields();返回指定对象域字段数组,主要包含该类自身的所有域,包括private等。
Method[] getMethods(); 返回指定对象域方法数组,主要包含该类及其超类的所有公有(public)域方法。
Method[] getDeclaredMethods();返回指定对象域方法数组,主要包含该类自身的所有域方法,包括private等。
Constructor[] getConstructors(); 返回指定对象构造函数数组,主要包含该类所有公有(public)域构造器。
Constructor[] getDeclaredConstructors();返回指定对象构造函数数组,主要包含该类所有域构造器。
int getModifiers(); 返回一个用于描述构造器、方法或域的修饰符的整型数值,使用Modifier类中的静态方法可以协助分析这个返回值。
String getName(); 返回一个用于描述构造器、方法和域名的字符串。
Class[] getParameterTypes(); 返回一个用于描述参数类型的Class对象数组。
Class[] getReturnType(); 返回一个用于描述返回值类型的Class对象。
1 private static void printConstructors(Class c1) {
2 Constructor[] constructors = c1.getDeclaredConstructors();
3 for (Constructor c : constructors) {
4 String name = c.getName();
5 System.out.print(" ");
7 if (modifiers.length() > 0)
8 System.out.print(modifiers + " ");
9 System.out.print(name + "(");
10
11 Class[] paramTypes = c.getParameterTypes();
12 for (int j = 0; j < paramTypes.length; ++j) {
13 if (j > 0)
14 System.out.print(",");
15 System.out.print(paramTypes[j].getName());
16 }
17 System.out.println(");");
18 }
19 }
20
21 private static void printMethods(Class c1) {
22 Method[] methods = c1.getDeclaredMethods();
23 for (Method m : methods) {
24 Class retType = m.getReturnType();
25 String name = m.getName();
26 System.out.print(" ");
27
28 String modifiers = Modifier.toString(m.getModifiers());
29 if (modifiers.length() > 0)
30 System.out.print(modifiers + " ");
31 System.out.print(retType.getName() + " " + name + "(");
32 Class[] paramTypes = m.getParameterTypes();
33 for (int j = 0; j < paramTypes.length; ++j) {
34 if (j > 0)
35 System.out.print(", ");
36 System.out.print(paramTypes[j].getName());
37 }
38 System.out.println(");");
39 }
40 }
41
42 private static void printFields(Class c1) {
43 Field[] fields = c1.getDecla