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 源类型 * @param 目标类型 * @return 转换后的目标对象 */ public static R transObject(T source, Class 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 源类型 * @param 目标类型 * @return 转换后的目标List对象 */ public static List transList(List sourceList, Class 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 源类型 * @param 目标类型 * @return 转换后的目标Page对象 */ public static Page transPage(Page sourcePage, Class targetClass) { if (sourcePage == null) { return new Page<>(); } // 创建一个新的 Page 对象用于存放转换后的目标类型对象 Page targetPage = new Page<>(sourcePage.getCurrent(), sourcePage.getSize(), sourcePage.getTotal()); // 转换列表并设置到 Page 对象中 List targetList = transList(sourcePage.getRecords(), targetClass); targetPage.setRecords(targetList); return targetPage; } }