在寫接口時,每次都要返回 Vo 對象,所以就封裝了一個拷貝方法#
public class BeanCopyUtils {
private BeanCopyUtils() {
}
public static <V> V copyBean(Object source,Class<V> clazz) {
//創建目標對象
V result = null;
try {
result = clazz.newInstance();
//實現屬性copy
BeanUtils.copyProperties(source, result);
} catch (Exception e) {
e.printStackTrace();
}
//返回結果
return result;
}
public static <O,V> List<V> copyBeanList(List<O> list, Class<V> clazz){
return list.stream()
.map(o -> copyBean(o, clazz))
.collect(Collectors.toList());
}
}
使用方法#
//Bean 拷貝
List<HotArticleVo> hotArticleVos =
BeanCopyUtils.copyBeanList(articles, HotArticleVo.class);