反射之getField()与getDeclaredField()的区别

遇到Class.getFields(), Class.getField(String), Class.getDeclaredFields(), Class.getDeclaredField(String)

Class.getMethods(), Class.getMethod(String, Class[]), Class.getDeclaredMethods(), Class.getDeclaredMethod(String, Class[])
主要的就是有没有Declared单词的区别,使用时有什么不同呢?下面是举一反三的例子!

父类

public class Parent {
    public String parent_public;
    protected String parent_protected;
    String parent_default;
    private String parent_private;
}

 

子类

public class Child extends Parent {
    public String child_public;
    protected String child_protected;
    String child_default;
    private String child_private;
}

 

测试类

import java.lang.reflect.Field;

public class reflectTest {
    @Test
    public void reflect(){
        System.out.println("getFields()");
        for (Field field : Child.class.getFields()) {
            System.out.println(field.getName());
        }
        System.out.println("---------------");
        System.out.println("getDeclaredFields()");
        for (Field declaredField : Child.class.getDeclaredFields()) {
            System.out.println(declaredField.getName());
        }
    }
}

运行结果

getFields()
child_public
parent_public
---------------
getDeclaredFields()
child_public
child_protected
child_default
child_private

总结

getFields()只能获取子类及其父类的public变量。

get getDeclaredFields()只能获取子类创建的所有变量

posted @ 2020-04-21 17:54  手握钢叉的猹  阅读(1517)  评论(0编辑  收藏  举报