JavaBean setter 方法调用错误 "wrong number of arguments"

JavaBean setter method invocation error "wrong number of arguments"

我正在尝试设置 JavaBean 的索引值,但我无法通过反射来做到这一点。 任何想法为什么会这样?如何通过反射调用setter?

public class Bean1111 {
    public void setColors(Color[] colors) {
        this.colors = colors;
    }
    public Color [] colors = {Color.RED, Color.green, Color.blue, Color.pink};

    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        Bean1111 bean = new Bean1111();
        Color[] colors = new Color[]{Color.RED,Color.BLACK};
        bean.getClass().getDeclaredMethods()[0].invoke(bean, colors); //exception  "java.lang.IllegalArgumentException: wrong number of arguments"
    }
}

出于某种原因,如果我执行此代码,编译器会将我的数组内联为多个对象,而不是数组对象

// with the same bean class
 public static void main(String[] args) throws Exception {
        Bean1111 bean = new Bean1111();
        Color[] colors = new Color[]{Color.RED,Color.BLACK, Color.WHITE};
        Expression expr = new Expression(bean, "setColors", colors);
        expr.execute();
        // java.lang.NoSuchMethodException: <unbound>=Bean1111.setColors(Color, Color, Color);
    }

你应该使用

bean.getClass().getDeclaredMethods()[0].invoke(bean, new Object[] {colors});

或:

bean.getClass().getDeclaredMethods()[0].invoke(bean, (Object) colors);

由于 invoke 方法采用 varargs 参数,因此您已明确告知您的数组是调用方法的单个参数。

将 getter 方法添加到 Bean1111 class 然后打印结果时:

Arrays.stream(bean.getColors()).forEach(System.out::println);

它给出输出:

RED
BLACK