2013-01-16 46 views
1

即時通訊類名(字符串)和類有幾個方法和 因爲它的動態(我可以得到任何類)我需要使用所有set方法並用數據更新它。 我該怎麼做?創建類的新的實例,作爲字符串和更新設置方法

要獲取類的字段我用下面的代碼

className = obj.getClassName(); 
Class<?> classHandle = Class.forName(className); 

例如這裏我需要更新firstName和姓氏

public class Person { 

private String id; 
    private String firstName; 
    private String lastName; 

    public void setLastName(String lastName) { 

     this.lastName = lastName; 
    } 

    public void setfirstName(String firstName) { 

     this.firstName = firstName; 
    } 

或不同類在這裏,我需要設置工資和工作描述

public class Job { 


    private double salery; 
    private String jobDescr; 


    public void setSalery(double salery) { 
    this.salery = salery; 
    } 

    public void setJobDescr(String jobDescr) { 
    this.jobDescr = jobDescr; 
    } 

} 
+0

查看'Class'的API。有所有你可能想要使用的方法。 – MrSmith42

回答

2

對於初學者來說,你做的很好。我假設你有一個Map<String, Object>的屬性設置:attributeMap

//this is OK 
className = obj.getClassName(); 
Class<?> classHandle = Class.forName(className); 

//got the class, create an instance - no-args constructor needed! 
Object myObject = classHandle.newInstance(); 

//iterate through all the methods declared by the class 
for(Method method : classHandle.getMethods()) { 
    //check method name 
    if(method.getName().matches("set[A-Z].*") 
     //check if it awaits for exactly one parameter 
     && method.getParameterTypes().length==1) { 

     String attributeName = getAttributeName(method.getName()); 
     //getAttributeName would chop the "set", and lowercase the first char of the name of the method (left out for clarity) 

     //To be extra nice, type checks could be inserted here... 
     method.invoke(myObject, attributeMap.get(attributeName));    

    } 
} 

當然,很多異常處理是必須要做的,這是什麼做只是一個基本的想法...

推薦閱讀:

+0

感謝您的回放,但我發現編譯錯誤並獲取parametertype - 查找(「設置[AZ]」)&& method.getParameterTypes){ 和也在getAttributeName和屬性映射 查找 - 我得到錯誤方法查找(字符串)是未定義的類型字符串 getParameterTypes - 無法解析或不是字段 方法getAttributeName(字符串)是未定義的類型... 屬性映射-attributeMap無法解析 –

+0

目前我有問題發現 –

+1

我編輯了一下答案。我犯了一些錯誤,find()不在String中,但是matches()是......當然,getParameterTypes不是字段,而是一個函數:getParameterTypes()。但是這並不是一個完整的例子 - 你必須提供getAttributeName()函數(查看註釋)和attributeMap Map 才能使其工作。但如果這些問題構成障礙,你很難克服,我建議開始尋找更低層次的編程練習...... – ppeterka

相關問題