2013-03-09 59 views
0

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

+0

你用'SecurityManager'运行吗? – 2013-03-09 21:40:42

+0

你有没有其他非静态的领域(公共或私人)在这个类? – 2013-03-09 21:42:06

+0

它在Win7 Java7-32bit上可以正常工作。另外'field.setAccessible(true);'对于您想要读取的公共字段不是必需的。 – Pshemo 2013-03-09 21:42:41

回答

3

所需包裹.get()在try-catch块中

String value = null; 

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

所以,你根本没有得到一个IllegalAccessException。你有一个编译错误,因为你没有捕获或声明一个检查的异常。下一次,请粘贴您获得的完整且准确的错误消息。并且不要混淆编译运行它的程序。 – 2013-03-09 22:10:11

+0

我想我只是盯着它太久了。 Eclipse给我一个“未处理的异常类型IllegalAccessException”,因为它抛出一个异常。 我是新来的Java和新的Eclipse。这是一个诚实的错误,也许可以在这个问题上得到更好的解释。 – Aeisor 2013-03-09 22:13:51