(转)Field getField(String name)与Field getDeclaredField(String name)的区别

Field getField(String name)返回已加载类声明的所有public成员变量的Field对象,包括从父类继承过来的成员变量,参数name指定成员变量的名称

而Field getDeclaredField(String name)不能获取从父类那继承过来的成员变量

***********************************************

 
    
1 package cn.com.vo;
2
3 public class Father {
4 public String name = " 父亲 " ;
5
6 public String sex = " " ;
7
8 public String getName() {
9 return name;
10 }
11
12 public void setName(String name) {
13 this .name = name;
14 }
15
16 public String getSex() {
17 return sex;
18 }
19
20 public void setSex(String sex) {
21 this .sex = sex;
22 }
23
24
25 }
26 +++++++++++++++++++++++++++++++++
27
28 package cn.com.vo;
29
30 public class Son extends Father{
31
32 // public String name;
33 public int age = 20 ;
34
35
36 }
37 =========================================
38
39 package cn.com.vo;
40
41 import java.lang.reflect.Constructor;
42 import java.lang.reflect.Field;
43 import java.lang.reflect.InvocationTargetException;
44 import java.lang.reflect.Method;
45
46 import cn.com.vo.UserVo;
47
48 public class TestReflect {
49
50 /**
51 * java反射机制
52 */
53 public static void main(String[] args) {
54 try {
55 // 类的动态加载
56 Class c = Class.forName( " cn.com.vo.Son " ); // 方式一
57 Son vo = (Son)c.newInstance();
58
59 Field f = c.getField( " name " );
60 System.out.println(f.get(vo));
61
62
63 // 注意:下段代码会报错,
64 /* Field f2=c.getDeclaredField("name");
65 System.out.println(f2.get(vo)); */
66
67 } catch (ClassNotFoundException e) {
68 // TODO Auto-generated catch block
69 e.printStackTrace();
70 } catch (SecurityException e) {
71 // TODO Auto-generated catch block
72 e.printStackTrace();
73 } catch (NoSuchFieldException e) {
74 // TODO Auto-generated catch block
75 e.printStackTrace();
76 } catch (InstantiationException e) {
77 // TODO Auto-generated catch block
78 e.printStackTrace();
79 } catch (IllegalAccessException e) {
80 // TODO Auto-generated catch block
81 e.printStackTrace();
82 }
83 }
84
85 }

转载于:https://www.cnblogs.com/keis/archive/2011/05/10/2042408.html

你可能感兴趣的:((转)Field getField(String name)与Field getDeclaredField(String name)的区别)