`

BeanUtils 的陷阱

阅读更多

由于BeanUtils 的美名远播,加之学艺不精;项目中想当然直接使用BeanUtils;结果华丽丽的掉进了陷阱;


且看下面场景:

1、待copy类

public class SiteSupplierTrade {

    private Long      longAttr;
    private String[]  StringArrayAttr;
    private Integer  integerAttr;
    private String    StringAttr;
    //set  get
}

 2、copy类

public class SiteSupplierTradeCopy {

    private Long     longAttr;
    private String[] StringArrayAttr;
    private Integer  integerAttr;
    private String   StringAttr;
    // set  get
}

3、copy

 public static void main(String[] args) {

        SiteSupplierTrade siteSupplierTrade = new SiteSupplierTrade();
        if (null != siteSupplierTrade) {
            SiteSupplierTrade siteSupplierTrade2 = new SiteSupplierTrade();
            SiteSupplierTradeCopy SiteSupplierTrade3 = new SiteSupplierTradeCopy();
            try {
                BeanUtils.copyProperties(siteSupplierTrade2, siteSupplierTrade);
                BeanUtils.copyProperties(SiteSupplierTrade3, siteSupplierTrade);
            } catch (Exception e) {
            }
            System.out.println(siteSupplierTrade2);
            System.out.println(SiteSupplierTrade3);
            try {
                PropertyUtils.copyProperties(siteSupplierTrade2, siteSupplierTrade);
                PropertyUtils.copyProperties(SiteSupplierTrade3, siteSupplierTrade);
            } catch (Exception e) {
            }
            System.out.println(siteSupplierTrade2);
            System.out.println(SiteSupplierTrade3);
        }
    }

 
4、结果:

SiteSupplierTrade[longAttr=0,StringArrayAttr={},integerAttr=0,StringAttr=<null>]
SiteSupplierTradeCopy[longAttr=0,StringArrayAttr={},integerAttr=0,StringAttr=<null>]

SiteSupplierTrade[longAttr=<null>,StringArrayAttr=<null>,integerAttr=<null>,StringAttr=<null>]

SiteSupplierTradeCopy[longAttr=<null>,StringArrayAttr=<null>,integerAttr=<null>,StringAttr=<null>]


5、结论:

1)、熟悉BeanUtils PropertyUtils的知道,这两兄弟的区别就是BeanUtils 会做类型转换,PropertyUtils不会,自然前者性能不如后者;

2)、其实还有一个副作用,观察结果标红的部分,发现BeanUtils 会将long、integer 初始化为0,string[]初始化为空数组,而不是copy一个null;

3)、对于依赖为空判断的应用来说就是一个悲剧。

 

 

本站支持 pay for your wishes

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics