Reflection

1. 获取Class对象

1 obj.getClass();
2 Class.forName();
3 T.class;

数组在调用getName()返回值形如"[Ljava.lang.Double"

1 obj.getClass().newInstance();  //调用默认无参构造函数创建一个对象
2 
3 //如果需要调用有参构造函数需使用Constructor的newInstance方法
4 
5 obj.getClass().getDeclaredConstructors();  //获取全部, 包括私有和受保护成员, 但包括父类的成员
6 obj.getClass().getConstructors();  //获取public成员

 

2. 获取成员对象

2.1 获取Constructor对象

1 Constructor[] constructors = obj.getClass().getDeclaredConstructor();
2 
3 String modifiers = Modifier.toString(constructors[0].getModifiers());
4 
5 String name = constructors[0].getName();
6 Class[] paramTypes = constructors[0].getParameterTypes();
7 String pName = paramTypes[0].getName();

 

2.2 获取Field对象

2.2.1 获取

 1 Field[] fields = obj.getClass().getDeclaredFields();
 2 Field[] fields = obj.getClass().getFields();
 3 
 4 Field field = obj.getClass().getField(name);//获取名称为name的public类型变量
 5 Field field = obj.getClass().getDeclaredField(name);//获取名称为name的变量
 6 
 7 String modifiers = Modifier.toString(fields[0].getModifiers());
 8 
 9 Class type = fields[0].getType();
10 String typeName = type.getName();
11 String name = fields[0].getName();
12 
13 /*
14 检查Field是否可写, 并试图设置其可写属性(Method也一样)
15 参考: xwork-core.jar: com.opensymphony.xwork2.injec.ContainerImpl$FieldInjector
16 if (!field.isAccessible()) {
17     SecurityManager sm = System.getSecurityManager();
18     try {
19         if (sm != null) sm.checkPermission(new ReflectPermission("suppressAccessChecks"));
20         field.setAccessible(true);
21     } catch(AccessControlException e) {
22         e.printStackTrace();
23     }
24 }
25 */
26 feild.setAccessible(true);//不严谨的写法
27 AccessibleObject.setAccessible(fileds, true);//批量处理
28 
29 Object value = fields[0].get(obj);//获取obj中变量field[0]的值
30 
31 //如果返回值为基本类型, 反射机制会自动将其打包到对应的包装类中

 

2.2.1 设置

1 f.setAccessible(true);
2 
3 fields[0].set(obj, value);//设置obj中变量fields[0]的值

 

2.3 获取Method对象

 1 //获得Method对象
 2 Method[] methods = obj.getClass().getDeclaredMethods();
 3 Method[] methods = obj.getClass().getMethods();
 4 
 5 //获得修饰符
 6 String modifier = Modifier.toString(methods[0].getModifiers());
 7 
 8 //获得返回类型
 9 String returnTypeName = method[0].getReturnType().getName();
10 
11 //获得方法名
12 String name = method[0].getName();
13 
14 //参数
15 Class[] paramTypes = method[0].getParameterTypes();
16 String paramName = paramTypes[0].getName();

 

posted @ 2012-12-12 08:45  堂哥  阅读(231)  评论(0编辑  收藏  举报