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 sourceToTarget(Object source, Class 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转化为List * * @param sourceList 实体类集合Collection * @param target 目标类DTO * @return 转化后的Collection */ public static List sourceToTarget(Collection sourceList, Class target){ if(sourceList == null){ return null; } ArrayList 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; } }