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

发布于 2024-10-09 20:19:10 字数 302 浏览 0 评论 0原文

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

Foo f = new Foo();

为 param1 的对象,我有字符串“param1”,并且我想以某种方式将“set”与它连接起来,如“set”+“param1”,然后将其应用到 f​​ 实例上:

f.setparam1("value");

对于 getter 也是如此。我知道反思会有所帮助,但我无法做到这一点。 请帮忙。谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

素衣风尘叹 2024-10-16 20:19:10

你可以做这样的事情。您可以使此代码更加通用,以便可以将其用于字段上的循环:

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

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文