反射之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