我需要使用反射来调用类的setter方法,代码如下:
try {
Method method = myObj.getClass().getMethod("set" + fieldName, new Class[] { value.getClass() });
method.invoke(myObj, value);
} catch (Exception ex) {
ex.printStackTrace();
}
该值是一个ArrayList,setter方法如下所示:
public void setNames(List names){
this.names = names;
}
运行此代码时会抛出java.lang.NoSuchMethodException异常,但是当setter方法参数类型从List更改为ArrayList时,它执行正常。有没有办法将setter方法参数保留在超类型中,并且在从类中获取方法时仍然使用反射而不手动提供参数的类型?