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