1

我正在获取类名(字符串),并且该类的 sets 方法很少,并且由于它是动态的(我可以获取任何类),因此我需要使用所有 sets 方法并使用 data 更新它。我怎样才能做到这一点 ?

要获取类字段,我使用以下代码

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

例如在这里我需要更新名字和姓氏

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;
  }

}
4

1 回答 1

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));            

   }
}

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

推荐阅读:

于 2013-01-16T15:17:27.123 回答