Java中VO、DO、PO、DTO之间的模型转换

模型转换

在现在微服务架构盛行的时期,很多业务存在model(vo/dao/po/dto…)的根据作用域不同而进行分类。

导致项目时常会有模型转换问题,需直接get/set或者for循环来处理,显的代码不美观,而且很麻烦,可使用一些工具类或自己实现

在这里插入图片描述

代码实现

/**
 * @author : zhang
 * @version : v1.0
 * @description 模型转换 Utils
 * @date : 2020/7/15 15:52
 */
public class ModelConverterUtils {

    /**
     * 创建类的一个实例
     *
     * @param beanClass
     *            类
     */
    public static <T> T newInstance(Class<T> beanClass) {
        try {
            return beanClass.newInstance();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 属性拷贝
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copyProperties(Object source, Object target){
        if (source == null) {
            return;
        }
        BeanUtils.copyProperties(source, target);
    }

    /**
     * 对象转换
     * @param source 源对象
     * @param targetClass 目标对象
     * @param <T> 目标对象class类型
     * @return 返回新的目标对象
     */
    public static <T> T convert(Object source, Class<T> targetClass) {
    	if(source == null ){
            return null;
        }
        T target = newInstance(targetClass);
        copyProperties(source, target);
        return target;
    }

    /**
     * 对象List转换
     * @param sources 源对象
     * @param targetClass 目标对象
     * @param <T> 目标对象class类型
     * @return 返回新的目标对象List
     */
    public static <T> List<T> convert(Collection<?> sources, Class<T> targetClass){
	    if(sources == null ){
            return null;
        }
        List<T> targets = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(sources)) {
            targets = sources.stream().map(x ->  convert(x, targetClass)).collect(Collectors.toList());
        }
        return targets;
    }

}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值