我正在查询数据库并获取结果集。在处理结果集时,我必须将值设置为相应的设置器。对于一个特定的列,我将得到像1、2、3、4、5等的值,直到20。
如果值是1,我必须将其分配给setValue1()如果值为2,则必须将其分配给setValue2(),依此类推,直到setValue20()。
示例:
if(dbObject.getValue()==1) {
userObject.setfoo1(dbObject.getValue());
}
if(dbObject.getValue()==2) {
userObject.setfoo2(dbObject.getValue());
}
.
.
if(dbObject.getValue()==20) {
userObject.setfoo20(dbObject.getValue());
}
我的目标是编写1个块来实现此功能,而不是我目前拥有20个块
提前感谢。
您需要使用反射来实现。尝试将以下函数添加到将调用setValueNN()方法的类中(实际上任何* .java文件都可以使用)。
//Assuming your object which contains the method ''setValueN()'' is ''MyObject''
// and what you read from yor database is a String - so your method is ''setValueN(String str)''
public static Method getSetterMethod(int index) {
Method mtd = MyObject.class.getDeclaredMethod("setValue" + index , new Class[]{String.class});
mtd.setAccessible(true);
return mtd;
}
然后您可以使用此Method对象来调用所需的方法:
Method mtd = getSetterMethod(3); // will give you ''setValue3(String str)''
mtd.invoke(methodParameter); // method parameter is what you want to set if you would have call your ''setValueN(methodParameter)'' method directly.
我希望有帮助。
使用反射,您可以做到。这是一个例子:
class SampleResultSet{
public void setfoo1(int i){
System.out.println(String.format("Invoked with %s", i));
}
public void setfoo2(int i){
System.out.println(String.format("Invoked with %s", i));
}
}
class Main {
public static void main(String[] args)
{
SampleResultSet s = new SampleResultSet();
int[] inputArray = new int[]{1, 2};
Method[] methods
= SampleResultSet.class.getMethods();
String methodNameTmpl = "setfoo%s";
for (int eachInpout : inputArray) {
try {
Method fooMethod = SampleResultSet.class.getMethod(String.format(methodNameTmpl, eachInpout), int.class);
fooMethod.invoke(s, eachInpout);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
}