反射之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()只能获取子类创建的所有变量


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM