如何使用反射定义动态setter和getter? [英] 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();
和参数的param1,我有字符串 参数1 和我某种程度上想concate 设定 与它比如set+param1然后将它应用于f实例:
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");
和getter相同。我知道反思会有所帮助,但我无法做到。
请帮忙。谢谢!
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("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();
}
这篇关于如何使用反射定义动态setter和getter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!