/**
* @description: 对象转换工具类 原理:BeanUtils.copyProperties方法(浅拷贝)
* @author: zk
* @since: 2022-04-26 19:00:04
*/
@Slf4j
public class ConvertUtil {
/**
* 列表转为某个对象列表
*
* @param e
* @param clz
* @param <E>
* @param <T>
* @return
*/
public static <E, T> List<T> convert(List<E> e, Class<T> clz) {
ArrayList<T> results = new ArrayList<>();
if (CollectionUtils.isEmpty(e)) {
return results;
}
for (E element : e) {
T result = null;
try {
result = clz.newInstance();
} catch (Exception ex) {
ex.printStackTrace();
log.error("object convert err ! {}",ex.getMessage());
}
BeanUtils.copyProperties(element, result);
results.add(result);
}
return results;
}
/**
* E对象转T对象
*
* @param e
* @param clz
* @param <E>
* @param <T>
* @return
*/
public static <E, T> T convert(E e, Class<T> clz) {
if (Objects.isNull(e)) {
return null;
}
T result = null;
try {
result = clz.newInstance();
} catch (Exception ex) {
ex.printStackTrace();
log.error("object convert err ! {}",ex.getMessage());
}
BeanUtils.copyProperties(e, result);
return result;
}
}
测试
?
?
|