Loading

Java之反射机制一:获取及其操作类的属性

1.实体类

public class Dog {
    private String color;

    public boolean hasTail;

    public boolean isHasTail() {
        return hasTail;
    }

    public void setHasTail(boolean hasTail) {
        this.hasTail = hasTail;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "color='" + color + '\'' +
                '}';
    }
}

2.通过java反射机制获取类的属性的值

@Test
public void test1(){
    Dog dog = new Dog();
    dog.setColor("白");
    Class clazz = dog.getClass();
    try {
        Field color = clazz.getDeclaredField("color");
        //设置即使该属性是private,也可以进行访问(默认是false)
        color.setAccessible(true);
        String c = color.get(dog).toString();
        System.out.println(dog);
    }catch (Exception e){
        e.printStackTrace();
    }
}

运行结果:

 

3.通过java反射机制设置类的属性

@Test
    public void test2(){
        Dog dog = new Dog();
        Class clazz = dog.getClass();
        try{
            Field color = clazz.getDeclaredField("color");
            color.setAccessible(true);
            color.set(dog,"黑");
            System.out.println(dog);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

 运行结果:

 4.getField方法和getDeclaredField方法两者区别(getFields和getDeclaredFields同理)

getField:只能获取类和其父类的public属性

getDeclaredField:该方法只可以获取类本身的属性(private public protected default),但不包括父类

实体类BigDog.java继承于Dog.java

public class BigDog extends Dog {
    private Integer age;

    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "BigDog{" +
                "age=" + age +
                '}';
    }
}

测试getFields方法:

@Test
    public void test(){
        BigDog dog  = new BigDog();
        Class dogClass = dog.getClass();
        //只能获取类及其父类的公有属性
        Field[] fields = dogClass.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
    }

 运行截图:

 测试getDeclaredFields方法:

@Test
    public void test3(){
        BigDog dog  = new BigDog();
        Class dogClass = dog.getClass();
        //能获取该类中所有的属性,但是不能获取父类的属性
        Field[] fields = dogClass.getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field);
        }
    }

运行截图:

 

posted @ 2020-03-19 23:59  秋风飒飒吹  阅读(882)  评论(0编辑  收藏  举报