新的业务场景需要一个新的订单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;
好吧,我算是能理解前辈为啥不辞艰辛了。