通过反射获取字段:
--
反射方法并调用时,静态方法可以不传递对象。
字段有点小不同,即使是静态字段也需要传递对象
以下是测试类:包括一个测试实体类:Girl.java,一个反射测试Demo.java
Girl.java:
1 package cn.rt.gwq;
2
3 public class Girl {
4
5 private int age = 18;
6 public int height = 168;
7 public static String name = "alice" ;
8
9 public Girl() {
10 // TODO Auto-generated constructor stub
11 }
12
13 public Girl(int age,int height,String name){
14 this.age = age;
15 this.height = height;
16 this.name = name;
17 }
18
19 }
Demo_FieldRflt:
1 package cn.rt.gwq;
2
3 import java.lang.reflect.Field;
4
5 import org.junit.Test;
6
7 public class Demo_FieldRflt {
8
9 /**
10 * 反射获取字段
11 * @throws Exception
12 */
13 @Test
14 public void test1() throws Exception{
15
16 Girl girl = new Girl(18,168,"alice");
17
18 //加载类
19 Class clazz = Class.forName("cn.rt.gwq.Girl");
20
21 //公有字段
22 Field height = clazz.getField("height");
23 int h = (int) height.get(girl);
24
25 //私有字段
26 Field age = clazz.getDeclaredField("age");
27 age.setAccessible(true);
28 int a = (int) age.get(girl);
29
30 //静态字段
31 Field name = clazz.getField("name");
32 String n = (String) name.get(girl);
33
34 //输出验证
35 System.out.println("name:"+n+",age:"+a+",height:"+h);
36 }
37
38 }