`

BeanUtils.copyProperties VS PropertyUtils.copyProperties

阅读更多

 BeanUtils.copyProperties VS  PropertyUtils.copyProperties 

作为两个bean属性copy的工具类,他们被广泛使用,同时也很容易误用,给人造成困然;比如:昨天发现同事在使用BeanUtils.copyProperties copy有integer类型属性的bean时,没有考虑到会将null转换为0,而后面的业务依赖于null来判断,导致业务出错。下面总结一下主要的注意点:

 

  • 大范围两个工具类都是对两个bean之前存在name相同的属性进行处理,无论是源bean或者目标bean多出的属性均不处理。


  • 具体到BeanUtils是相同name并且类型之间支持转换属性可以处理,而PropertyUtils不支持类型转换必须是类型和name一样才处理。


  • 对null的处理:PropertyUtils支持为null的场景;BeanUtils对部分属性不支持null的情况,具体为下:

        1)、date类型不支持:异常 dateorg.apache.commons.beanutils.ConversionException: No value                  

          specified for 'Date'     

        2)、Ineger、Boolean、Long等不支持: 转为0;     

        3)、string:支持,保持null;

 

  • 关于类型转换的例子:     

       源bean有属性:   private Long    dateVal;

       目标bean有属性:private Date    dateVal;

       使用 PropertyUtils,会保错:Caused by: java.lang.IllegalArgumentException: argument type mismatch

       使用BeanUtils,则相当于new date(dateVal),网上传言java.util.Date不支持,就测试来说无论是 sql    

       util 都是ok

 

  • 对于自定义的对象类型属性  都是浅copy :

       比如都有属性:private Base  base;   Base有一个属性String Test;

       new.getBase().setTest("new");

       那么old.getBase().getTest()也为new

 

  • 性能:get,set《PropertyUtils《BeanUtils

  • BeanUtils的高级功能org.apache.commons.beanutils.Converter接口可以自定义类型之间的转化。PropertyUtils没有。 

 

0
1
分享到:
评论
1 楼 GGGGeek 2018-12-25  
Integer null转为0的情况是什么时候

相关推荐

Global site tag (gtag.js) - Google Analytics