反射-Field-Java

 1 import java.lang.reflect.Field;
 2 
 3 /**
 4  * Created with IDEA
 5  * author:foreign
 6  * Date:2019/9/30
 7  * Time:10:10
 8  */
 9 public class ReflectionFk {
10     public static void main(String[] args) throws IllegalAccessException {
11         Class clazz = PersonFk.class;
12         //1 获取所有public的字段
13         Field[] fields = clazz.getFields();
14         for (Field field : fields) {
15             System.out.println("public的字段:" + field);
16         }
17         try {
18             //1.1 根据指定的名字获取public的字段
19             Field variable = clazz.getField("desc");
20             System.out.println("指定name的public字段:" + variable);
21         } catch (NoSuchFieldException e) {
22             e.printStackTrace();
23         }
24         Field[] fields1 = clazz.getFields();
25         for (Field field : fields1) {
26             //2 获取变量的名称
27             String name = field.getName();
28             System.out.println("变量的名称:" + name);
29             //3 获取变量的类型
30             Class<?> type = field.getType();
31             System.out.println("变量的类型:" + type);
32             //4 获取变量的值
33             PersonFk personFk = new PersonFk();
34             Object o = field.get(personFk);
35             System.out.println("获取变量的值:" + o);
36             //4.1 设置变量的值
37             field.set(personFk,o);
38         }
39     }
40 }

 

posted @ 2019-09-30 10:20  青稞123  阅读(193)  评论(0编辑  收藏  举报