如何使用反射定义动态setter和getter?

时间:2010-12-30 07:10:26

标签: java reflection setter getter

我有一个来自资源包的循环中的类的字符串,字段名称列表。我创建一个对象,然后使用循环我想为该对象设置值。例如,对象

Foo f = new Foo();

使用参数param1,我有字符串“param1”,我想以某种方式将“set”与“set”+“param1”连接起来,然后将其应用于f实例:

f.setparam1("value");

和吸气剂相同。我知道反思会有所帮助,但我无法做到。 请帮忙。谢谢!

2 个答案:

答案 0 :(得分:9)

你可以这样做。您可以使此代码更通用,以便您可以使用它来循环字段:

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

答案 1 :(得分:7)