需求:
项目当中各层对象经常需要转换,VO、PO、DTO
实现:
1、引入pom依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.2</version>
</dependency>
2、创建工具类
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import java.util.List;
public class BeanUtil {
/**
* Java对象Copy
*/
public static <T> T beanCopy(Object source, Class<T> targetType) {
String sourceJson = JSON.toJSONString(source);
return JSON.parseObject(sourceJson, targetType);
}
/**
* Java列表Copy
*/
public static <T> List<T> beanCopyList(List<?> sourceList, Class<T> targetType) {
String sourceListJson = JSON.toJSONString(sourceList);
return JSON.parseArray(sourceListJson, targetType);
}
/**
* Java分页列表Copy
*/
public static <T> PageInfo<T> beanCopyPage(List<?> sourceList, Class<T> targetType) {
List<T> list = beanCopyList(sourceList, targetType);
PageInfo pageInfo = new PageInfo(sourceList);
pageInfo.setList(list);
return pageInfo;
}
}