我读了一大堆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?如果我删除该字段,我可以在LogCat中看到以下行。线:
System.out | domain
System.out | class java.lang.String
引用:
使用反射获取Java成员变量值的缺陷
反射:通过反射加载的类中的常量变量
通过反射访问Java静态final ivar值
需要在try-catch块中包装。get()
String value = null;
try {
value = (String)field.get(null);
// Do something with value
} catch (IllegalAccessException e) {
// Handle exception
}