【问题标题】:Invoking setText() through reflection only if an object has an specific annotaion仅当对象具有特定注释时才通过反射调用 setText()
【发布时间】:2015-09-04 05:43:04
【问题描述】:

我正在尝试通过反射设置多个不同组件(JButton、JLabel 等)的文本。我还在稍后要更改的字段中使用注释。

例如,我有以下代码:

public class MainWindow {

    @UsesTextChanger
    private JButton btn1;

    @UsesTextChanger
    private JLabel lb1;

    public void ChangeTexts() {

        for (Field field: MainWindow.class.getDeclaredFields()) {
            field.setAccessible(true);
            UsesTextChanger usesTextChanger = field.getAnnotation(UsesTextChanger.class);
            if (usesTextChanger != null){   

                try {
                    Method method = field.getType().getMethod("setText", new Class[]{String.class});
                    method.invoke(field, "my new text");

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }       
    }
}

我收到以下异常:

java.lang.IllegalArgumentException: object is not an instance of declaring class

有没有办法获取该字段的实例,以便我可以正确调用setText() 方法?

我还尝试通过循环遍历我的所有组件来采取另一种方法(该代码目前仅在第一层中有效),实际上 setText() 有效,但是我不知道如何检查是否注释在那里:

for (Component component: this.frame.getContentPane().getComponents()) {
    try {
        boolean componentUsesTextChangerAnnotation = true; // Is there a way to check if an annotation exists in an instanced object?
        if (componentUsesTextChangerAnnotation) {
            Method method = component.getClass().getMethod("setText", new Class[]{String.class});
            method.invoke(component, "my new text");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

谢谢!

【问题讨论】:

  • 您可以使用您的第一种方法,将MainWindow.class.getDeclaredFields() 替换为component.getClass().getDeclaredFields() 对吧?

标签: java reflection field invoke


【解决方案1】:

您试图在 Field 上调用该方法 - 而您实际上想在对象内字段的 value 上调用它。

你想要:

Method method = field.getType().getMethod("setText", String.class);
Object target = field.get(this);
method.invoke(target, "my new text");

(顺便说一句,我使用 Class.getMethod 有一个可变参数参数来简化对它的调用。)

【讨论】:

  • 这正是我想要的!在我的代码中完美运行。谢谢!
猜你喜欢
  • 2018-07-15
  • 2014-06-18
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多