繁体   English   中英

根据值动态设置setter

[英]Dynamically set the setter based on the value

我正在查询数据库并获取结果集。 当我处理结果集时,我必须将值设置为相应的设置器。 对于一个特定的列,我将获得 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 个块

提前致谢。

使用反射你可以做到这一点。 这是一个例子:

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[] dbObjects = new int[]{1, 2};
        Method[] methods
                = SampleResultSet.class.getMethods();
        String methodNameTmpl = "setfoo%s";
        for (int dbObject : dbObjects) {
            try {
                Method fooMethod = SampleResultSet.class.getMethod(String.format(methodNameTmpl, dbObject), int.class);
                fooMethod.invoke(s, dbObject);
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }

    }
}

您需要使用反射来实现这一点。 尝试将以下 function 添加到将调用setValueNN()方法的 class(实际上任何 *.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;
}

然后你可以使用这个方法object 来调用你想要的方法:

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.

我希望这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM