前言
日常开发中,实体类只是单纯的作为一个个体,请求和返回通常再次编写请求和返回对应的实体。但是在做数据库查询时如果使用mybatis-generator等生成插件,返回的实体还是原本的实体类。
CopyUtil
public class CopyUtil {
/**
* 单体复制
*/
public static <T> T copy(Object source, Class<T> clazz) {
if (source == null) {
return null;
}
T obj = null;
try {
obj = clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}
BeanUtils.copyProperties(source, obj);
return obj;
}
/**
* 列表复制
*/
public static <T> List<T> copyList(List source, Class<T> clazz) {
List<T> target = new ArrayList<>();
if (!CollectionUtils.isEmpty(source)){
for (Object c: source) {
T obj = copy(c, clazz);
target.add(obj);
}
}
return target;
}
}
结语
本工具类适用于大多数情况,具体情况看个人进行修改。