BeanCopier和BeanUtils复制两个对象间的相同属性,实现BeanCopier静态缓存

新的业务场景需要一个新的订单List接口
不希望改到老的。
做了个新的对象(其实就是加了几个属性)
订单对象的字段复杂的一批,从数据库处理成给前端的对象比较繁琐,直接用的以前的函数。
然后,需要把老对象的属性copy到新对象里再做处理。
一开始下意识的用了
BeanUtils.copyProperties(source, target);
把source复制到target

当然,由于这是个list
时间理所当然的超了
看了下一些类似场景的转换,他们竟然写了几十行
this.xx = source.xxx

我人傻了,网上一通搜索,然后换成了据说效率更高的
BeanCopier copier = BeanCopier.create(source.class,target.class,false);
copier.copy(source,target,null);

还是超时,查了下是create太耗时了,干脆写成静态的,这样就不用每次都来create了

public class Converter {

    private static Map<CopierIdentity, BeanCopier> copierCache = Maps.newConcurrentMap();

    public static <T> T copy(T target, Object source) {
        BeanCopier copier = getCopier(source.getClass(), target.getClass());
        copier.copy(source, target, false);
        return target;
    }

    public static <T> T convert(Class<T> targetClass, Object source) {
        try {
            T target = targetClass.newInstance();
            BeanCopier copier = getCopier(source.getClass(), targetClass);
            copier.copy(source, target, false);
            return target;
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private static BeanCopier getCopier(Class<?> source, Class<?> target) {
        CopierIdentity identity = new CopierIdentity(source, target);
        BeanCopier copier;
        if (copierCache.containsKey(identity)) {
            copier = copierCache.get(identity);
        } else {
            copier = BeanCopier.create(source, target, true);
            copierCache.putIfAbsent(identity, copier);
        }
        return copier;
    }

    @AllArgsConstructor
    @Data
    @EqualsAndHashCode
    private static class CopierIdentity {
        private Class<?> source;
        private Class<?> target;
    }

}

这样终于不超时了。
这样的效率比直接用BeanUtils.copyProperties快上数十倍。

我这个场景是够用了。

但是比不上几十行this.xxx = source.xxx;
好吧,我算是能理解前辈为啥不辞艰辛了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值