Dto转Entity工具类
程序员文章站
2022-06-14 23:08:57
...
package com.ekingwin.jc.mall.system.utils;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
public class ToDtoUtils {
public static void toDto(Class pc, Object po, Class dc, Object dto) throws Exception {
//获取实体类的全部属性
Field[] dcFields = dc.getDeclaredFields();
Field[] pcFields = pc.getDeclaredFields();
for (Field dcField : dcFields) {
//AccessibleTest 类中的成员变量为private
//取消属性的访问权限控制,即使private属性也可以进行访问
dcField.setAccessible(true);
String dcName = dcField.getName();
//屏蔽序列化的字段
if ("serialVersionUID".equals(dcName)) {
continue;
}
//遍历entity
for (Field pcField : pcFields) {
pcField.setAccessible(true);
String pcName = pcField.getName();
if (dcName.equals(pcName)) {
String pcMethodName = "get" + StringUtils.capitalize(pcName);
Method pcMethod = pc.getDeclaredMethod(pcMethodName);
dcField.set(dto, pcMethod.invoke(po));
}
}
}
}
public static <IN,OUT> OUT toAllDto(IN in,Class<OUT> clazz) {
OUT out = null;
try {
out= clazz.newInstance();
ToDtoUtils.toDto(in.getClass(), in, out.getClass(), out);
} catch (Exception e) {
e.printStackTrace();
}
return out;
}
/**
* 分页
* @param inPageInfo
* @param clazz
* @param <T>
* @param <E>
* @return
*/
public static <T,E> PageInfo<T> toPageDto(PageInfo<E> inPageInfo, Class<T> clazz){
PageInfo<T> outPageInfo=new PageInfo<T>();
copy(inPageInfo,outPageInfo);
List<E> inList=inPageInfo.getList();
List<T> outList=inList.stream().map(in -> ToDtoUtils.toAllDto(in,clazz)).collect(Collectors.toList());
outPageInfo.setList(outList);
return outPageInfo;
}
private static <E, T> void copy(PageInfo<E> inPageInfo, PageInfo<T> outPageInfo) {
outPageInfo.setSize(inPageInfo.getSize());
outPageInfo.setEndRow(inPageInfo.getEndRow());
outPageInfo.setHasNextPage(inPageInfo.isHasNextPage());
outPageInfo.setHasPreviousPage(inPageInfo.isHasPreviousPage());
outPageInfo.setIsFirstPage(inPageInfo.isIsFirstPage());
outPageInfo.setIsLastPage(inPageInfo.isIsLastPage());
outPageInfo.setNavigateFirstPage(inPageInfo.getNavigateFirstPage());
outPageInfo.setNavigateLastPage(inPageInfo.getNavigateLastPage());
outPageInfo.setNavigatepageNums(inPageInfo.getNavigatepageNums());
outPageInfo.setNavigatePages(inPageInfo.getNavigatePages());
outPageInfo.setNextPage(inPageInfo.getNextPage());
outPageInfo.setPageNum(inPageInfo.getPageNum());
outPageInfo.setPages(inPageInfo.getPages());
outPageInfo.setPageSize(inPageInfo.getPageSize());
outPageInfo.setPrePage(inPageInfo.getPrePage());
outPageInfo.setStartRow(inPageInfo.getStartRow());
outPageInfo.setTotal(inPageInfo.getTotal());
}
}