[英]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
參考文獻:
需要將.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.