gongzuming
2024-09-19 a768dc3daa04d35fedfbe75c0a59b9b2545b85c4
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
65
66
67
68
69
70
71
72
73
package com.mzl.flower.utils;
 
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
 
public class ConverterUtil {
 
    /**
     * 单个对象的转换
     * @param source 源对象
     * @param targetClass 目标类的类型
     * @param <T> 源类型
     * @param <R> 目标类型
     * @return 转换后的目标对象
     */
    public static <T, R> R transObject(T source, Class<R> targetClass) {
        if (source == null) {
            return null;
        }
        try {
            R targetObject = targetClass.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(source, targetObject);
            return targetObject;
        } catch (Exception e) {
            throw new RuntimeException("对象转换失败", e);
        }
    }
 
    /**
     * List对象的转换
     * @param sourceList 源List对象
     * @param targetClass 目标类的类型
     * @param <T> 源类型
     * @param <R> 目标类型
     * @return 转换后的目标List对象
     */
    public static <T, R> List<R> transList(List<T> sourceList, Class<R> targetClass) {
        if (sourceList == null || sourceList.isEmpty()) {
            return new ArrayList<>();
        }
        return sourceList.stream()
                .filter(Objects::nonNull)
                .map(sourceObject -> transObject(sourceObject, targetClass))
                .collect(Collectors.toList());
    }
 
    /**
     * Page对象的转换
     * @param sourcePage 源Page对象
     * @param targetClass 目标类的类型
     * @param <T> 源类型
     * @param <R> 目标类型
     * @return 转换后的目标Page对象
     */
    public static <T, R> Page<R> transPage(Page<T> sourcePage, Class<R> targetClass) {
        if (sourcePage == null) {
            return new Page<>();
        }
 
        // 创建一个新的 Page 对象用于存放转换后的目标类型对象
        Page<R> targetPage = new Page<>(sourcePage.getCurrent(), sourcePage.getSize(), sourcePage.getTotal());
 
        // 转换列表并设置到 Page 对象中
        List<R> targetList = transList(sourcePage.getRecords(), targetClass);
        targetPage.setRecords(targetList);
        return targetPage;
    }
}