1 package reflet;2 3 import java.util.List;4 public class person5 {6 public String name="aaaaa";7 private int password=123;8 private static int age=456;9 }
1 package reflet; 2 3 import java.lang.reflect.Field; 4 5 import org.junit.Test; 6 7 8 public class demo4 { 9 //反射字段: public String name="aaaaa";10 @Test11 public void test1() throws Exception12 {13 person p=new person();14 Class clazz=Class.forName("reflet.person");15 Field f=clazz.getField("name");16 String name=(String)f.get(p);//获取字段的值17 Class type=f.getType();//获取字段的的类型18 System.out.println(name);//打印字段的值19 System.out.println(type);//打印字段的类型20 21 //设置字段的值22 f.set(p, "nihao");23 System.out.println(p.name);24 25 }26 //反射字段: public String name="aaaaa";的另一种写法27 @Test28 public void test11() throws Exception29 {30 person p=new person();31 Class clazz=Class.forName("reflet.person");32 Field f=clazz.getField("name");33 34 35 System.out.println(f.get(p));//打印字段的值36 37 38 }39 //反射字段:private int password=123;40 @Test41 public void test2() throws Exception42 {43 person p=new person();44 Class clazz=Class.forName("reflet.person");45 Field f=clazz.getDeclaredField("password");46 f.setAccessible(true);47 int name=(int)f.get(p);//获取字段的值48 Class type=f.getType();//获取字段的的类型49 System.out.println(name);//打印字段的值50 System.out.println(type);//打印字段的类型 51 }52 //反射字段: private static int age=456;53 @Test54 public void test3() throws Exception55 {56 person p=new person();57 Class clazz=Class.forName("reflet.person");58 Field f=clazz.getDeclaredField("age");59 f.setAccessible(true);60 int name=(int)f.get(p);//获取字段的值61 Class type=f.getType();//获取字段的的类型62 System.out.println(name);//打印字段的值63 System.out.println(type);//打印字段的类型 64 }65 66 }