使用java反射调用setter方法 [英] Invoking setter method using java reflection
问题描述
我需要使用反射来调用类的setter方法,代码如下:
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();
}
值
是一个 ArrayList
,setter方法如下:
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 $ c运行此代码时抛出$ c>,但当setter方法参数类型从
List
更改为 ArrayList
时执行得很好。有没有办法将setter方法参数保持在超类型中并且仍然使用反射而无需在从类中获取方法时手动给出参数类型?
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?
推荐答案
与其他答案相反,有一个非常简单的解决方案。请参阅 java.beans.Statement
。它为您提供了一种执行任意反射代码的方法,而无需担心实际与正式类型(以及其他一些事情)。
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).
这篇关于使用java反射调用setter方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!