模型互转
在现在微服务架构盛行的时期,很多业务存在model(vo/dao/po/dto…)的根据作用域不同而进行分类。
导致项目时常会有模型转换问题,需直接get/set或者for循环来处理,显的代码不美观,而且很麻烦,可使用一些工具类或自己实现。
单个类直接的copy,可使用BeanUtils.copyProperties工具类。
如有Collection类型的场景进行互转,则需要自行实现。写了一个工具类方便使用
代码实现:
/**
* @author : zhang
* @version : v1.0
* @description 模型转换 Utils
* @date : 2020/7/15 15:52
*/
public class ModelConverterUtils {
/**
* 创建类的一个实例
*
* @param beanClass
* 类
*/
public static <T> T newInstance(Class<T> beanClass) {
try {
return beanClass.newInstance();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
/**
* 属性拷贝
* @param source 源对象
* @param target 目标对象
*/
public static void copyProperties(Object source, Object target){
if (source == null) {
return;
}
BeanUtils.copyProperties(source, target);
}
/**
* 对象转换
* @param source 源对象
* @param targetClass 目标对象
* @param <T> 目标对象class类型
* @return 返回新的目标对象
*/
public static <T> T convert(Object source, Class<T> targetClass) {
T target = newInstance(targetClass);
copyProperties(source, target);
return target;
}
/**
* 对象List转换
* @param sources 源对象
* @param targetClass 目标对象
* @param <T> 目标对象class类型
* @return 返回新的目标对象List
*/
public static <T> List<T> convert(Collection<?> sources, Class<T> targetClass){
List<T> targets = Lists.newArrayList();
if (!CollectionUtils.isEmpty(sources)) {
targets = sources.stream().map(x -> convert(x, targetClass)).collect(Collectors.toList());
}
return targets;
}
}
本文暂时没有评论,来添加一个吧(●'◡'●)