從BeanUtils的一個坑談起

BeanUtils能夠將參數封裝成一個bean,方法 setProperty,能夠對屬性進行賦值。可是尤爲是要注意的是它會對屬性設置默認值,並且默認值會有歧義。 java

好比說Bean TestBean 的某個屬性的類型是Integer, this

TestBean testBean = new TestBean();
try {
    BeanUtils.setProperty(testBean, "testProperty", null)
} catch (Exception ex) {..... }
System.out.println("testProperty的值爲:"+testBean.getTestPropety);

其結果將會輸入爲0,這無疑是有坑的。 spa

與這個做用相似的Spring MVC有一個BaseCommandController也是能夠將請求參數封裝成Bean,可是null code

的值不會轉換爲默認值。使用的時候切記。 orm

若是BeanUtils也想不轉換爲類型(如 Integer)的默認值(如0),能夠使用以下: ip

try {
    ConvertUtils.register(new IntegerConverter(null), Integer.class);
    BeanUtils.setProperty(testBean,"testProperty",null)
} catch(Exception ex){
    ......
}


或者 get

PropertyUtils.getWriteMethod(PropertyUtils.getPropertyDescriptor(this, propertyName)).invoke(this, new Object[]{null});
相關文章
相關標籤/搜索