dto 转换为Do 工具类

该代码片段提供了一个公共工具类`CommonBeanUtils`,包含两个静态方法用于将DTO对象转换为DO对象以及将DO对象列表转换为DTO对象列表。方法使用Spring的BeanUtils.copyProperties进行属性复制,处理了空值和异常情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cheng
 */
public class CommonBeanUtils {

    /**
     * dto 转换为Do 工具类
     */
    public static <T> T dtoTransfer(Object sourceEntity, Class<T> targetClass) {
        // 判断dto是否为空!
        if (sourceEntity == null) {
            return null;
        }
        // 判断DoClass 是否为空
        if (targetClass == null) {
            return null;
        }
        try {
            T newInstance = targetClass.newInstance();
            BeanUtils.copyProperties(sourceEntity, newInstance);
            // Dto转换Do
            return newInstance;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * do 转换为Dto 工具类
     */
    public static <T> List<T> dtoListTransfer(List<?> sourceEntityList, Class<T> targetClass) {
        // 判断dto是否为空!
        if (CollectionUtils.isEmpty(sourceEntityList)) {
            return null;
        }
        // 判断DoClass 是否为空
        if (targetClass == null) {
            return null;
        }
        try {
            List<T> objects = new ArrayList<>();
            for (Object object : sourceEntityList) {
                T newInstance = targetClass.newInstance();
                BeanUtils.copyProperties(object, newInstance);
                objects.add(newInstance);
            }
            // Dto转换Do
            return objects;
        } catch (Exception e) {
            return null;
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值