cn.cliveyuan.robin.base.util.BeanCopyUtils Maven / Gradle / Ivy
package cn.cliveyuan.robin.base.util;
import cn.cliveyuan.robin.base.common.Pagination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @author Clive Yuan
* @date 2020/12/24
*/
public class BeanCopyUtils {
private static final Logger logger = LoggerFactory.getLogger(BeanCopyUtils.class);
/**
* 对象浅拷贝
*
* @param source 源对象
* @param targetClass 目标对象类
* @param 类
* @return
*/
public static T copy(Object source, Class targetClass) {
// AssertUtils.notNull(source, "source is required");
if (Objects.isNull(source)) {
return null;
}
AssertUtils.notNull(targetClass, "targetClass is required");
try {
T targetObject = targetClass.getDeclaredConstructor().newInstance();
BeanUtils.copyProperties(source, targetObject);
return targetObject;
} catch (Exception e) {
logger.error("copy error", e);
throw new RuntimeException(e);
}
}
/**
* @param sourceList 源对象列表
* @param targetClass 目标对象类
* @param 源类
* @param 目标类
* @return
*/
public static List copyList(List sourceList, Class targetClass) {
AssertUtils.notNull(sourceList, "sourceList is required");
AssertUtils.notNull(targetClass, "targetClass is required");
if (sourceList.size() == 0) {
return new ArrayList<>();
}
return sourceList.stream().map(x -> copy(x, targetClass)).collect(Collectors.toList());
}
/**
* @param sourcePagination 源对象分页
* @param targetClass 目标对象类
* @param 源类
* @param 目标类
* @return
*/
public static Pagination copyPagination(Pagination sourcePagination, Class targetClass) {
AssertUtils.notNull(sourcePagination, "sourcePagination is required");
AssertUtils.notNull(targetClass, "targetClass is required");
if (Objects.isNull(sourcePagination.getDataList())) {
return Pagination.buildEmpty();
}
List list = copyList(sourcePagination.getDataList(), targetClass);
Pagination pagination = new Pagination<>();
pagination.setDataList(list);
pagination.setTotalCount(sourcePagination.getTotalCount());
pagination.setHasNext(sourcePagination.isHasNext());
pagination.setPageNo(sourcePagination.getPageNo());
pagination.setPageSize(sourcePagination.getPageSize());
pagination.setTotalPages(sourcePagination.getTotalPages());
return pagination;
}
}