【问题标题】:How to define dynamic setter and getter using reflection?如何使用反射定义动态setter和getter?
【发布时间】:2010-12-30 07:10:25
【问题描述】:

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

Foo f = new Foo();

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

f.setparam1("value");

和 getter 一样。我知道反思会有所帮助,但我无法做到。 请帮忙。谢谢!

【问题讨论】:

  • 如果您正在为将要存在的所有内容制作 setter 和 getter,听起来您应该考虑将其公开。
  • 即使属性是公开的,如何使用反射使字符串表现得像字段?
  • 为什么要自己实现?您可以使用 Lombok (projectlombok.org/features)。只需在您的类中添加@Getter 注解,它就会为每个字段生成一个getter 方法(注意:它不是源代码生成工具)。
  • 您好,请发给您 Foo 课程的详细信息

标签: java reflection setter getter


【解决方案1】:

你可以做这样的事情。你可以让这段代码更通用,这样你就可以用它来循环字段:

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

【讨论】:

  • confirmMsg 将被替换为 methodName... 它有效,非常感谢 :)
  • 嗨,请帮帮我。我需要更多详细信息。
【解决方案2】:

【讨论】:

  • 提供一些有关链接资源如何回答问题的信息会很有帮助。
猜你喜欢
  • 2019-10-18
  • 1970-01-01
  • 2012-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多