技术干货学习@IT·互联网

构建功能最强、性能最好的Java BeanCopy类库

2017-08-08  本文已影响0人  TuYang
本文所提到的类库已经开源到GITHUB,读者可下载源码并提宝贵意见。

转载请注明出处: http://www.jianshu.com/p/9a136ecd3838

问题

在现有的项目中,由于采用了PO/DTO/VO模型,导致需要大量的代码进行Java对象间的拷贝操作。通常的做法是取一个对象的get方法,设置到另一个对象的set方法上去:

    public MaterialInfoVO getMaterialInfo(String materialId) {
        
        MaterialInfo materialInfo = this.materialDao.findById(materialId);
        
        MaterialInfoVO materialInfoVO = new MaterialInfoVO();
        materialInfoVO.setMaterialId(materialInfo.getId());
        materialInfoVO.setType(materialInfo.getType());
        materialInfoVO.setArticles(new ArrayList<ArticleInfoVO>());
        
        List<ArticleInfo> articles = materialInfo.getArticles();
        for (ArticleInfo article : articles) {
            ArticleInfoVO articleInfoVO = new ArticleInfoVO();
            materialInfoVO.getArticles().add(articleInfoVO);
            
            articleInfoVO.setArticleId(article.getId());
            articleInfoVO.setTitle(article.getTitle());
            articleInfoVO.setContent(article.getContent());
            articleInfoVO.setContentSourceUrl(article.getContentSourceUrl());
            articleInfoVO.setDigest(article.getDigest());
            articleInfoVO.setShowCoverPic(article.getShowCoverPic());
            articleInfoVO.setShowOrder(article.getShowOrder());
            articleInfoVO.setThumbMediaId(article.getThumbMediaId());
            articleInfoVO.setUrl(article.getUrl());
            articleInfoVO.setContentSourceUrl(article.getContentSourceUrl());
            
        }
        
        return materialInfoVO;
    }

然而,大量类似重复的代码到处可见,代码重复度太高,而且很容易视觉疲劳,导致字段遗漏。由此萌生了改善的想法,希望能达到以下的目的:

    public MaterialInfoVO getMaterialInfo(Integer materialId) {
        MaterialInfo materialInfo = this.materialDao.findById(materialId);
        return BeanCopyUtils.copyBean(materialInfo,MaterialInfoVO.class);
    }

需求分析

为了改善代码,能够自动的将一个类的属性Copy到另一个类中,并且还需要满足以下的特定需求:

现有库调研

在目前比较通用的BeanCopy类库中,有如下的几个类库:

上面是目前能在市面上找到的几个比较通用的类库。然而,这些类库却很难满足上述的需求:

Library 属性名称映射 基本类型转换 忽略拷贝 数组拷贝 集合拷贝 自定义转换 性能
apache BeanUtil. copyProperties X X X X X X 惨不忍睹
apache PropertyUtils. copyProperties X X X X X X 惨不忍睹
spring BeanUtils. copyProperties X X X X 还能接受
cglib BeanCopier X X X X X 难用 优秀
ezmorph BeanMorpher X X X X X X 惨不忍睹

也许有些库的用法还不得知,但很难全部功能都满足。看来只能自己造轮子了。

库接口设计

函数接口

为了自己的轮子能否方便的使用,在接口函数设计上可尽量简单。
函数调用方式如下:

  // 使用class方式
  ToBean toBean = BeanCopyUtils.copyBean(fromBean, ToBean.class);
  // 使用对象方式
  ToBean toBean = new ToBean();
  BeanCopyUtils.copyBean(fromBean, toBean);

为了能达到上述的需求,需要引入一些注解来进行配置。


                                           @BeanCopySource(source=FromBean.class)          
    public class FromBean {                public class ToBean {                           
                                                                                           
        private boolean beanBool;              private Boolean beanBool;                   
        private byte beanByte;                 private Byte beanByte;                      
        private char beanChar;                 private Character beanChar;                 
        private short beanShort;               private Short beanShort;                    
        private int beanInt;                   private Integer beanInt;                    
        private Long beanLong;                 private long beanLong;                      
        private Float beanFloat;               private float beanFloat;                    
        private Double beanDouble;             private double beanDouble;                  
        private String beanString;             private String beanString;                  
                                                                                           
                                               @CopyProperty(convertor=DateConvertor.class)
        private Date beanDate;                 private String beanDate;                    
                                                                                           
        private int[] beanIntArray;            private int[] beanIntArray;                 
                                                                                           
                                               @CopyProperty                               
        private FromBean2 bean2;               private ToBean2 bean2;                      
                                                                                           
                                               @CopyCollection(targetClass=ToBean3.class)  
        private List<FromBean3> bean3List;     private List<ToBean3> bean3List;            
                                                                                           
                                               @CopyProperty                               
        private FromBean4[] bean4Array;        private ToBean4[] bean4Array;               
                                                                                           
        // getters and setters...              @CopyProperty(property="beanInt")           
    }                                          private int beanId;                         
                                                                                           
                                               @CopyProperty(property="bean2.beanString")  
                                               private String bean2String;                 
                                               
                                               // getters and setters...
                                           }

现在问题又来了,如果ToBean是第三方类库的,无法在ToBean上加注解,怎么办?这能难倒我吗?这儿仅需要提供一个Option类,将所有注解的内容加到Option类中,让Option类代替ToBean来做配置。

@BeanCopySource(source=FromBean.class)
public class ToBeanOption {
    
    private Boolean beanBool;
    private Byte beanByte;
    private Character beanChar;
    private Short beanShort;
    private Integer beanInt;
    private long beanLong;
    private float beanFloat;
    private double beanDouble;
    private String beanString;
    
    @CopyProperty(convertor=DateConvertor.class)
    private String beanDate;
    
    private int[] beanIntArray;

    @CopyProperty
    private ToBean2 bean2;
    
    @CopyCollection(targetClass=ToBean3.class)
    private List<ToBean3> bean3List;
    
    @CopyProperty
    private ToBean4[] bean4Array;
    
    @CopyProperty(property="beanInt")
    private int beanId;
    
    @CopyProperty(property="bean2.beanString")
    private String bean2String;
    // getters and setters can be empty.
}

调用方法也非常简单:

  // 使用class方式
  ToBean toBean = BeanCopyUtils.copyBean(fromBean, ToBean.class, ToBeanOption.class);
  // 使用对象方式
  ToBean toBean = new ToBean();
  BeanCopyUtils.copyBean(fromBean, toBean, ToBeanOption.class);

是不是有点羡慕?

自定义数据转换

为了支持自定义数据转换,需要引入接口,以方便自定义转换要求:

public interface BeanCopyConvertor<S, T> {
    abstract public T convertTo(S object);
}

具体实现举例:

public class GendorConvertor implements BeanCopyConvertor<Integer, String> {

    @Override
    public String convertTo(Integer object) {
        if( object == 1 ) 
            return "Male";
        if( object == 2) 
            return "Female";
        return "Unknown";
    }
}

当然,也需要在注解上标明:

    @CopyProperty(convertor=GendorConvertor.class)
    private String gendor;

实现及优化

具体的实现步骤不表,仅说优化及其它考虑。

优化方案

减少依赖

类库设计之初是为了通用使用,因此要尽量减少对其它类库的引用。因此,除了必须要引用的javassist类库之外,全部自我实现相关功能,不引用其它的类库。
更为甚者,如果要在javassist类都无法运行的环境中使用此库,也可以通过修改此类库的全局配置,切换到用反射的方式上运行此库。

缺省集合类

再做集合拷贝的时候,对于集合类的实现类可以通过全局配置的方式切换为自定义的实现类。 例如List对应的实现类,缺省为ArrayList。但是如果想使用LinkedList,可以通过全局配置来进行切换。

性能

通过对不同类库循环调用的方法来测试各个类库的性能。

Library 1 time 100 times 10000 times 1000000 times 10000000 times
apache BeanUtil.copyProperties 1 12 128 9963 99879
apache PropertyUtils.copyProperties 0 2 56 5564 55651
spring BeanUtils.copyProperties 0 2 5 473 4700
ezmorph BeanMorpher 1 4 67 6769 68051
cglib BeanCopier.create 1 1 2 2 87 843
cglib BeanCopier.create 2 0 0 0 10 98
BeanCopyUtils.copyBean 1 0 0 0 21 196
BeanCopyUtils.copyBean 2 0 0 0 11 97
native Copy 0 0 0 10 88

结尾和后续

目前第一版本已经完成,后续会加上对注解的检查函数,以避免注解配置错误。同时由于是第一版本,测试的并不是很充分,还需要大量的测试来保证正确性。

关于作者

作者很懒,很少发表技术有关的话题文章。同时作者在软件开发上混了快20年,辗转于C、C++,Java,Object-C各个开发语言之间;做过Windows、Linux、Android、iOS以及Java后台开发,管理过20+以上的团队。但更多的,却是想当一个默默奉献的码农。

上一篇 下一篇

猜你喜欢

热点阅读