对象转化工具类
使用spring提供的BeanUtils
工具类进行封装
BeanCovertUtils.java
package top.hyqstudio.utils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* @author 追梦路上的孩子
* @version 1.0
* @date 2024/1/9 11:15
*/
public class BeanConvertUtils extends BeanUtils {
/**
* 单个对象转化
*
* @param source 数据源
* @param targetSupplier 目标对象
* @return copy后的对象
*/
public static <S, T> T convertTo(S source, Supplier<T> targetSupplier) {
if (ObjectUtils.isEmpty(source) || ObjectUtils.isEmpty(targetSupplier)) {
return null;
}
T t = targetSupplier.get();
copyProperties(source, t);
return t;
}
/**
* List集合转化
*
* @param sources 数据源
* @param targetSupplier 目标集合
* @return copy后的集合
*/
public static <S, T> List<T> convertListTo(List<S> sources, Supplier<T> targetSupplier) {
if (null == sources || null == targetSupplier) {
return null;
}
return sources.stream().map(s -> convertTo(s, targetSupplier)).collect(Collectors.toList());
}
/**
* Page集合转化
*
* @param source 数据源
* @param targetSupplier 目标Page
* @return copy后的Page
*/
public static <S, T> Page<T> covertPage(Page<S> source, Supplier<T> targetSupplier) {
Page<T> target = new Page<>();
copyProperties(source, target);
target.setRecords(convertListTo(source.getRecords(), targetSupplier));
return target;
}
}