0

I am querying the database and getting the result set. When I am processing the result set I would have to set the value to the respective setter. I will be getting values like 1, 2, 3, 4, 5 and so on till 20 for one particular column.

If a value is 1 I have to assign it to setValue1() If the value is 2 then I have to assign it to setValue2() and so on till setValue20().

Example:

if(dbObject.getValue()==1) {
userObject.setfoo1(dbObject.getValue());
}
if(dbObject.getValue()==2) {
userObject.setfoo2(dbObject.getValue());
}
.
.
if(dbObject.getValue()==20) {
userObject.setfoo20(dbObject.getValue());
}

My goal is to write 1 block to achieve this functionality instead of 20 blocks that I currently have

Thanks in advance.

Vamsi
  • 619
  • 3
  • 9
  • 22

2 Answers2

1

You need to use reflection to achieve this. Try adding following function to the class on which the setValueNN() method will be invoked (actually any *.java file will work).

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

Then you can use this Method object to invoke the method you want:

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.

I hope that helps.

alperozge
  • 136
  • 7
1

Using reflection you can do that. Here is an example:

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

    }
}
stackguy
  • 188
  • 5