2013-03-09 64 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