Invoking setter method using java reflection

java, reflection

Solution

Contrary to other answers, there is a really simple solution. See `java.beans.Statement`. It gives you a way to execute arbitrary reflective code without having to worry about actual vs formal types (and a few other things).

Problem

I need to invoke the setter methods of a class using reflection, and the code is as below: ``` try { Method method = myObj.getClass().getMethod("set" + fieldName, new Class[] { value.getClass() }); method.invoke(myObj, value); } catch (Exception ex) { ex.printStackTrace(); } ``` The `value` is an `ArrayList` and the setter method is as below: ``` public void setNames(List<String> names){ this.names = names; } ``` A `java.lang.NoSuchMethodException` is thrown when running this code, but when the setter method parameter type is changed to `ArrayList` from `List` it executes fine. Is there a way to keep the setter method parameter in super type and still use reflection without manually giving the type of the parameter when getting the method from the class?

Original source