简体   繁体   English

如何使用反射定义动态的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();

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: 使用参数param1,我有字符串“ param1”,我想以某种方式将“ set”连接起来,例如“ set” +“ param1”,然后将其应用于f实例,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM