Dilini Rajapaksha Dilini Rajapaksha - 5 months ago 58
Java Question

Invoking setter method using java reflection

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?

EJP EJP
Answer

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).

Comments