我读过一大堆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