14

I've a list of strings, field names, of a class in a loop from resource bundle. I create an object and then using loop i want to set values for that object. For example, for object

Foo f = new Foo();

with parameter param1, I have string "param1" and I somehow want to concate "set" with it like "set"+"param1" and then apply it on f instance as:

f.setparam1("value");

and same for getter. I know reflection will help but I couldn't manage to do it. Please help. Thanks!

jmj
  • 237,923
  • 42
  • 401
  • 438
wasimbhalli
  • 5,122
  • 8
  • 45
  • 63
  • if you are making setters and getters for everything that ever will exist, it sounds like you should consider making things public. – EnabrenTane Dec 30 '10 at 07:12
  • even if attributes are public, how can I use reflection so that the strings behave as fields? – wasimbhalli Dec 30 '10 at 07:16
  • 1
    Why implement it yourself? You can use Lombok (http://projectlombok.org/features). Just add `@Getter` annotation to your class and it will generate a getter method for each field (note: it's not source code generation tool). – rodion Dec 30 '10 at 07:25
  • Hi, Please post you Foo class details – nurealam11 Jun 09 '15 at 10:06

2 Answers2

14

You can do something like this. You can make this code more generic so that you can use it for looping on fields:

Class aClass = f.getClass();
Class[] paramTypes = new Class[1];
paramTypes[0] = String.class; // get the actual param type

String methodName = "set" + fieldName; // fieldName String
Method m = null;
try {
    m = aClass.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException nsme) {
    nsme.printStackTrace();
}

try {
    String result = (String) m.invoke(f, fieldValue); // field value
    System.out.println(result);
} catch (IllegalAccessException iae) {
    iae.printStackTrace();
} catch (InvocationTargetException ite) {
    ite.printStackTrace();
}
Ankit Bansal
  • 4,962
  • 1
  • 23
  • 40
7

Apache Commons BeanUtils does it.

卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130