Java - 通过反射访问公共成员

时间:2013-03-09 21:34:40

标签: java reflection illegalaccessexception

我已经阅读了大量的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中看到以下几行,如果我删除了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

1 个答案:

答案 0 :(得分:3)

需要将.get()包装在try-catch块中

String value = null;

try {
    value = (String)field.get(null);
    // Do something with value
} catch (IllegalAccessException e) {
    // Handle exception
}
相关问题