使用 MapStruct
- 丢弃掉那些BeanUtils工具类吧,MapStruct真香!!!
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) {
dcField.setAccessible(true);
String dcName = dcField.getName();
if ("serialVersionUID".equals(dcName)) {
continue;
}
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;
}
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());
}
}