Dto与Entity相互转换的工具类

public class Dto2Entity {
    private static final Logger log=LoggerFactory.getLogger(Dto2Entity.class);
// 使用多线程安全的Map来缓存BeanCopier,由于读操作远大于写,所以性能影响可以忽略
        public static ConcurrentHashMap<String, BeanCopier> beanCopierMap = new ConcurrentHashMap<String, BeanCopier>();
         
        /**
         * 通过cglib BeanCopier形式
         * @param source
         * @param target
         */
        public static void copyProperties(Object source, Object target) {
            String beanKey = generateKey(source.getClass(), target.getClass());
            BeanCopier copier = null;
            copier = BeanCopier.create(source.getClass(), target.getClass(), false);
            beanCopierMap.putIfAbsent(beanKey, copier);// putIfAbsent已经实现原子操作了。
            copier = beanCopierMap.get(beanKey);
            copier.copy(source, target, null);
        }
 
        private static String generateKey(Class<?> class1, Class<?> class2) {
            return class1.toString() + class2.toString();
        }
 
    /**
         ×通过常规反射形式
     * DTO对象转换为实体对象。如命名不规范或其他原因导致失败。
     * @param t 源转换的对象
     * @param e 目标转换的对象
     * 
     */
    public static <T,E> void transalte(T t,E e){
        Method[] tms=t.getClass().getDeclaredMethods();
        Method[] tes=e.getClass().getDeclaredMethods();
        for(Method m1:tms){
            if(m1.getName().startsWith("get")){
                String mNameSubfix=m1.getName().substring(3);
                String forName="set"+mNameSubfix;
                for(Method m2:tes){
                    if(m2.getName().equals(forName)){
                                            // 如果类型一致,或者m2的参数类型是m1的返回类型的父类或接口
                        boolean canContinue = m2.getParameterTypes()[0].isAssignableFrom(m1.getReturnType());
                        if (canContinue) {
                            try {
                                m2.invoke(e, m1.invoke(t));
                                break;
                            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
                                // TODO Auto-generated catch block
                                log.debug("DTO 2 Entity转换失败");
                                e1.printStackTrace();
                            }
                        }
                    }
                }
            }
             
        }
        log.debug("转换完成");
         
    }
     
     
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值