从BeanUtils的一个坑谈起

BeanUtils可以将参数封装成一个bean,方法 setProperty,可以对属性进行赋值。但是尤其是要注意的是它会对属性设置默认值,而且默认值会有歧义。

比如说Bean TestBean 的某个属性的类型是Integer,

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

其结果将会输入为0,这无疑是有坑的。

与这个作用类似的Spring MVC有一个BaseCommandController也是可以将请求参数封装成Bean,但是null

的值不会转换为默认值。使用的时候切记。

如果BeanUtils也想不转换为类型(如 Integer)的默认值(如0),可以使用如下:

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


或者

PropertyUtils.getWriteMethod(PropertyUtils.getPropertyDescriptor(this, propertyName)).invoke(this, new Object[]{null});

转载于:https://my.oschina.net/anheitongyi/blog/150062

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值