簡體   English   中英

Java-通過反射訪問公共成員

[英]Java - accessing public members via reflection

我已經閱讀了很多SO問題,但似乎找不到答案。

我有以下課程:

public class DatabaseStrings {
    public static final String domain = 
        "CREATE TABLE IF NOT EXISTS domain (" +
            "_id INT UNSIGNED, " +
            "account VARCHAR(20) NOT NULL DEFAULT '', " +
            "domain TINYINT(1) DEFAULT 0, " +
            "domain_string VARCHAR(20) DEFAULT '', " +
            "user_id INT UNSIGNED DEFAULT 0" +
        ");";
}

在其他地方,我正在嘗試訪問以下字符串:

for(Field field : DatabaseStrings.class.getDeclaredFields()) {
    field.setAccessible(true); // I don't know if this is necessary, as the members are public

    System.out.println(field.getName());
    System.out.println(field.getType());
    String value = (String) field.get(null); // This line throws an IllegalAccessException inside Eclipse.
    // Do something with value
}

為什么會收到IllegalAccessException? 如果刪除field.get行,我可以在LogCat中看到以下行:

System.out    |    domain
System.out    |    class java.lang.String

參考文獻:

通過反射獲取Java中的成員變量值的陷阱

反射:通過反射加載的類中的常量變量

通過反射訪問Java靜態最終ivar值

需要將.get()包裝在try-catch塊中

String value = null;

try {
    value = (String)field.get(null);
    // Do something with value
} catch (IllegalAccessException e) {
    // Handle exception
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM