在我正在编写的模型中,我有一个带有签名public void setFoo(int newFoo)的方法。我使用下面的代码从我的控制器中调用它:
protected void setModelProperty(String propertyName, Object newValue) {
for (AbstractModel model: registeredModels) {
try {
Method method = model.getClass().
getMethod("set"+propertyName, new Class[] {
newValue.getClass()
}
);
method.invoke(model, newValue);
} catch (Exception ex) {
// Handle exception.
System.err.println(ex.toString());
}
}
}像controller.setModelProperty("Foo",5);这样调用此方法会导致抛出异常:java.lang.NoSuchMethodException: foo.bar.models.FooModel.setFoo(java.lang.Integer) --它看起来像是将int装箱为Integer,这与setFoo的签名不匹配。
有没有办法说服这个反射代码将5 (或者我传入的任何int )作为一个整数传递,而不进行装箱?或者我必须在我的模型中创建public void setFoo(Integer newFoo)并显式拆箱,然后调用原始setFoo?
发布于 2010-07-08 23:24:26
当调用setModelProperty()时,newValue被装箱为整数。这是唯一可以调用它的方法;'int‘不是instanceof对象。newValue.getClass()返回“整数”,因此对getMethod()的调用失败。
如果你想在这里使用原语,你需要一个特殊版本的setModelProperty。或者,您可以编写一个方法setFoo(整数)。
或者更一般地说,你可以这样写:
if (newValue.getClass()==Integer.class) {
// code to look for a method with an int argument
}https://stackoverflow.com/questions/3205098
复制相似问题