3、反射-Field

 

类的属性

1、获取字段

  获取全部字段:getDeclaredField()

  获取某一个字段:getDeclaredField(String name)

2、获取指定对象指定的字段的值

  get(Object obj):私有的需要调用:setAccessible(true)

3、设定指定对象指定的值

  set(Object obj,Object value)

 

public class Person {
    String name;
    private int age;


    public Person() {
    }
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

 

      Class clazz = Class.forName("cn.com.mrchengs.field.Person");

        //1、获取所有字段
        //共有的私有的均能获取
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields){
            System.out.println(field.getName());
        }

        //2、获取指定名字的Field
        //共有的私有的都能获取得到
        Field field = clazz.getDeclaredField("age");
        System.out.println(field.getName());
        Field field1 = clazz.getDeclaredField("name");
        System.out.println(field1.getName());

 

       //3、获取指定对象的Field的值
        Person person = new Person("MrChengs",22);
        Field field = clazz.getDeclaredField("age");
     //对于私有的属性需要设置 field.setAccessible(
true); Field field1 = clazz.getDeclaredField("name"); Object age = field.get(person); Object name = field1.get(person); System.out.println(age); System.out.println(name);

        //4、设置值
        Person person = new Person("MrChengs",22);
        Field field = clazz.getDeclaredField("age");
        field.setAccessible(true);
        field.set(person,33);
        System.out.println(field.get(person));

 

 

 对于工具方法同时可以参考Method的使用以及相关父类中的方法

 

 

posted @ 2019-05-27 21:54  MrChengs  阅读(409)  评论(0编辑  收藏  举报