From 35309b932b738d5a8537e53207d28004a8da0f89 Mon Sep 17 00:00:00 2001
From: gongzuming <gongzuming>
Date: 星期五, 20 九月 2024 17:17:04 +0800
Subject: [PATCH] Merge remote-tracking branch 'origin/master-v2'

---
 src/main/java/com/mzl/flower/utils/ConverterUtil.java |   73 ++++++++++++++++++++++++++++++++++++
 1 files changed, 73 insertions(+), 0 deletions(-)

diff --git a/src/main/java/com/mzl/flower/utils/ConverterUtil.java b/src/main/java/com/mzl/flower/utils/ConverterUtil.java
new file mode 100644
index 0000000..dfca4e6
--- /dev/null
+++ b/src/main/java/com/mzl/flower/utils/ConverterUtil.java
@@ -0,0 +1,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;
+    }
+}

--
Gitblit v1.9.3