1

我已经阅读了一大堆 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?如果我删除 field.get 行,我可以在 LogCat 中看到以下行:

System.out    |    domain
System.out    |    class java.lang.String

参考:

使用反射在 Java 中获取成员变量值的陷阱

反射:通过反射加载的类中的常量变量

通过反射访问Java静态最终ivar值

4

1 回答 1

4

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

String value = null;

try {
    value = (String)field.get(null);
    // Do something with value
} catch (IllegalAccessException e) {
    // Handle exception
}
于 2013-03-09T22:01:22.177 回答