| 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; | 
|     } | 
| } |