2017-03-05 62 views
1

使用java反射時,我們可以設置專用字段而不必告訴參數類型。使用Java反射設置專用字段

例如,如果這是我的Child類,

package reflection; 

public class Child { 

    private String name; 
    private Integer value; 
    private boolean flag; 


    public String getLName() 
    { 
     return this.name; 
    } 

    public void setName(String name) 
    { 
     this.name = name; 
    } 

    public Integer getValue() 
    { 
     return this.value; 
    } 

    public void setValue(Integer value) 
    { 
     this.value = value; 
    } 

    public boolean getFlag() 
    { 
     return this.flag; 
    } 

    public void setFlag(boolean flag) 
    { 
     this.flag = flag; 
    } 

    public String toString() 
    { 
     return "Name" + this.name; 
    } 
} 

我要將此Child類的字段我Tester類。

package reflection; 

public class Tester { 

    public static void main(String args[]) throws Exception 
    { 



     Class<?> clazz = Class.forName("reflection.Child"); 
     Object cc = clazz.newInstance(); 
     cc.getClass().getMethod("setName", String.class).invoke(cc,"AAA"); 
    } 
} 

在這裏,我設置的值爲Name字段。 在線,

cc.getClass().getMethod("setName", String.class).invoke(cc,"AAA"); 

我已經使用String.class。有沒有辦法做到這一點,而不必告訴字段類型。 Java能否以某種方式自動識別類型? 這是因爲我將從csv文件獲取名稱,值和標誌數據,並且我想使用循環將所有三個字段設置在一行中。 我將聲明一個String數組與價值觀 - 「的setName」,「setValue方法」和「setFlag」,然後我想用以下

cc.getClass().getMethod(array[index]).invoke(cc,data); 

我知道上面的說法是錯誤的東西,但有一些替代這個?

+1

循環遍歷類的方法,並找到一個名爲setName的。祈禱它沒有超載。請注意,這與私人領域無關。你在這裏調用公共方法,而不是設置私人領域。這就是說,就像幾乎所有與反思相關的問題一樣,反思可能不是解決問題的好方法。爲什麼不使用包含例如'n - > c.setName(n)'的消費者而不是數組字符串? –

回答

2

獲取所有的方法,並找到它的匹配,其中有關於參數輸入信息:

String name; 
String value; 
Method[] methods = Child.class.getMethods(); 
for (Method method : methods) { 
    if (!method.getName().equals(name)) 
     continue; 
    Class<?> paramType = method.getParameterTypes()[0]; 
    //You will have to figure how to convert the String value to the parameter. 
    method.invoke(child, paramType.cast(value)); // for example 
} 
+0

有沒有辦法循環遍歷所有方法? –

+0

@GrzegorzGórkiewicz除非你知道參數類型,你說你不知道。如果你知道參數類型,你可以調用'Child.class.getMethod(name,parameterClass)'來得到確切的方法。 – Bohemian

+0

但是參數類型總是......'value.getClass()'...即'data.getClass()'如我的答案或? –

0

你可以使用Apache共享FieldUtils.writeDeclaredField

Child childObject = new Child(); 
FieldUtils.writeDeclaredField(childObject, "name", "John", true);