我讀過一大堆SO問題,我似乎無法找到答案。Java - 通過反射訪問公共成員
我有以下類:
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?我可以在logcat中看到以下行,如果我刪除field.get行:
System.out | domain
System.out | class java.lang.String
參考文獻:
Pitfalls in getting member variable values in Java with reflection
Reflection: Constant variables within a class loaded via reflection
Accessing Java static final ivar value through reflection
你用'SecurityManager'運行嗎? – 2013-03-09 21:40:42
你有沒有其他非靜態的領域(公共或私人)在這個類? – 2013-03-09 21:42:06
它在Win7 Java7-32bit上可以正常工作。另外'field.setAccessible(true);'對於您想要讀取的公共字段不是必需的。 – Pshemo 2013-03-09 21:42:41