2010-01-24 59 views
17

如何設置或獲取名稱爲動態並存儲在字符串變量中的類中的字段?Java:如何通過存儲在變量中的名稱訪問類的字段?

public class Test { 

    public String a1; 
    public String a2; 

    public Test(String key) { 
     this.key = 'found'; <--- error 
    } 

} 
+0

雖然有這樣做的正確理由,但如果您正在嘗試這樣做,您可能會做出非常錯誤的事情。 – 2010-01-24 16:24:06

+0

你的代碼示例很混亂。 – 2015-03-26 12:22:17

回答

29

你必須使用反射:

下面是一個處理公共領域簡單案例的例子。如果可能,更好的選擇是使用屬性。

import java.lang.reflect.Field; 

class DataObject 
{ 
    // I don't like public fields; this is *solely* 
    // to make it easier to demonstrate 
    public String foo; 
} 

public class Test 
{ 
    public static void main(String[] args) 
     // Declaring that a method throws Exception is 
     // likewise usually a bad idea; consider the 
     // various failure cases carefully 
     throws Exception 
    { 
     Field field = DataObject.class.getField("foo"); 
     DataObject o = new DataObject(); 
     field.set(o, "new value"); 
     System.out.println(o.foo); 
    } 
} 
+0

set()問我兩個參數,Object和value, 爲什麼不只是值?第一個參數是什麼? - Field classField = this.getClass()。getField(objField.getName()); \t \t \t \t classField.set(Object,Value) – ufk 2010-01-24 13:39:56

+0

感謝該示例清除了所有內容:) – ufk 2010-01-24 13:52:23

+1

@ufk:第一個參數是要爲其設置字段的對象。請注意,您通過查詢類獲得了Field實例 - 沒有任何東西將其鏈接到該類的特定實例。 – 2010-01-24 13:53:54

0
Class<?> actualClass=actual.getClass(); 

Field f=actualClass.getDeclaredField("name"); 

上面的代碼就足夠了。

object.class.getField("foo"); 

不幸的是,上面的代碼不適合我,因爲類有空的字段數組。

相關問題