DTO,PO,VO等对象之间的转换都可以用
public class BeanConvertUtils {
/**
* 对象转换
* @param source 原数据
* @param clazz 目标类
* @return 入参不合法时返回null
*/
public static <T> T convert(Object source, Class<T> clazz) {
if (source == null || clazz == null){
return null;
}
try {
T target = clazz.newInstance();
BeanUtils.copyProperties(source, target);
return target;
} catch (InstantiationException e){
throw new RuntimeException("对象转换异常");
} catch (IllegalAccessException e){
throw new RuntimeException("对象转换异常");
}
}
/**
* 对象list转换
*
* @param sources 原数据
* @param clazz 目标类
* @return 入参不合法时返回空集合
*/
public static <T> List<T> convertList(List<?> sources, Class<T> clazz) {
if (CollectionUtils.isEmpty(sources) || clazz == null) {
return Collections.emptyList();
}
List<T> targets = Lists.newArrayList();
sources.stream().forEach(source -> targets.add(convert(source, clazz)));
return targets;
}
}