1

Im trying to set indexed value of JavaBean and i cannot do that with reflection. Any ideas why is this happening? How to invoke setter by reflection?

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"
    }
}

for some reason if i'll do this code, compiler just inline my array as an multiple objects, but not as an array object

// 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);
    }
Michael
  • 13
  • 3

1 Answers1

2

You should use

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

Or :

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

As invoke method takes varargs parameter you to have explicitly tell that your array is a single argument for invoked method.

When adding a getter method to your Bean1111 class and then printing the result :

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

It gives the output :

RED
BLACK
Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63