开发者

How to define dynamic setter and getter using reflection?

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 ha开发者_开发技巧ve 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!


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


Apache Commons BeanUtils does it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜