我正在尝试设置JavaBean的索引值,而我不能通过反射来做到这一点。 任何想法为什么会这样?如何通过反射调用设置器?
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);
}
答案 0 :(得分:1)
您应该使用
bean.getClass().getDeclaredMethods()[0].invoke(bean, new Object[] {colors});
或:
bean.getClass().getDeclaredMethods()[0].invoke(bean, (Object) colors);
由于invoke
方法使用varargs参数,因此您必须明确告诉您数组是被调用方法的单个参数。
在您的Bean1111
类中添加一个getter方法,然后打印结果时:
Arrays.stream(bean.getColors()).forEach(System.out::println);
它给出输出:
RED
BLACK