反射类的字段
1 package reflet; 2 3 import java.util.List; 4 public class person 5 { 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 @Test 11 public void test1() throws Exception 12 { 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 @Test 28 public void test11() throws Exception 29 { 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 @Test 41 public void test2() throws Exception 42 { 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 @Test 54 public void test3() throws Exception 55 { 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 }