liusheng
2025-04-16 4613099dca2d4e1c7b46a69a98bb4c210312ac57
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.ruoyi.common.utils;
 
import org.springframework.beans.BeanUtils;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
 
/**
 * DTO和entity相互转化工具类
 *
 * @author liusheng
 * @date 2023/5/06
 */
public class DtoConversionUtils {
 
    /**
     * entity转化为DTO
     *
     * @param source 实体类entity
     * @param target 目标类DTO
     * @return 转化后的DTO
     */
    public static <T> T sourceToTarget(Object source, Class<T> target){
        if(source == null){
            return null;
        }
        T targetObject = null;
        try {
            targetObject = target.newInstance();
            BeanUtils.copyProperties(source, targetObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return targetObject;
    }
 
    /**
     * List<entity>转化为List<DTO>
     *
     * @param sourceList 实体类集合Collection<entity>
     * @param target     目标类DTO
     * @return 转化后的Collection<DTO>
     */
    public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target){
        if(sourceList == null){
            return null;
        }
 
        ArrayList<T> targetList = new ArrayList<>(sourceList.size());
        try {
            for(Object source : sourceList){
                T targetObject = target.newInstance();
                BeanUtils.copyProperties(source, targetObject);
                targetList.add(targetObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return targetList;
    }
}