创建以字符串形式出现的类的新实例并更新sets方法

时间:2013-01-16 15:02:34

标签: java reflection

我得到了类名(字符串),并且该类有几个方法和 因为它的动态(我可以得到任何类)我需要使用所有的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;
  }

}

1 个答案:

答案 0 :(得分: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));            

   }
}

当然,要做很多异常处理,这只是要做什么的基本思路......

推荐阅读: