gpt4 book ai didi

java - 创建以字符串形式出现的类的新实例并更新集合方法

转载 作者:行者123 更新时间:2023-11-30 04:32:17 25 4
gpt4 key购买 nike

我正在获取类名(字符串),并且该类有很少的集合方法和由于它是动态的(我可以得到任何类),我需要使用所有的集合方法并用 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;
}

或者不同的类(class),我需要设置薪水和工作描述

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

}

最佳答案

首先,你所做的很好。我假设你有一个 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));

}
}

当然,还有很多异常处理要做,这只是要做的事情的基本想法...

推荐阅读:

关于java - 创建以字符串形式出现的类的新实例并更新集合方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14361343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com