我正在从Java 1.6迁移某个项目 - > 1.8和问题是 Apache Commons库(迁移一些旧版本 - > commons-beanutils-1.9.3.jar)。
我有这个扩展HasMap的Foo类,让我们说它加载了一些标志(我在实际例子中只剩下一个有20多个属性)
public class Foo extends HashMap<String, Object> {
public String getSomeFlag(){
return super.get("someFlag");
}
public void setSomeFlag(String SomeFlag){
super.put("someFlag", SomeFlag);
}
public void setSomeFlag(boolean SomeFlag){
if(SomeFlag)
super.put("someFlag", "Y");
else
super.put("someFlag", "N");
}
}
较旧版本的commons库不允许类型转换(Boolean to String),但现在显然没有强制执行。
Foo foo = new Foo();
foo.setSomeFlag("N");
System.out.println("FooFlag value: " + foo.getSomeFlag());
Boolean someFlagBoolean = new Boolean(true);
try {
PropertyUtils.setProperty(foo, "someFlag", someFlagBoolean); //i expect error here but it passes this line
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("FooString value: " + foo.getSomeFlag());
在旧版本的公共库中,异常被抛出这一行,这很好,我们处理它(为简单起见省略了代码)。
PropertyUtils.setProperty(foo, "someFlag", someFlagBoolean );
输出如下:
FooFlag value: N
FooString value: true
在执行PropertyUtils.setProperty
时是否有办法强制执行类型检查期待此错误
9.04.2018. 16:22:34 org.apache.commons.beanutils.PropertyUtilsBean invokeMethod
SEVERE: Method invocation failed.
Throwable occurred: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:1773)
at org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:1759)
at org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1641)
at org.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:1677)
at org.apache.commons.beanutils.PropertyUtils.setProperty(PropertyUtils.java:559)
at hr.etna.framework.common.object.ObjectMapperHelper.setAttribute(ObjectMapperHelper.java:69)