java之Spring中如何实现对象数组复制呢?
下文笔者将编写一个扩展方法,实现对象数组之间的复制操作,如下所示
实现思路:
1.通过遍历数组中的元素
2.借助spring的BeanUtils.copyProperties将元素的属性复制
采用以上方式实现元素复制
例
import org.springframework.beans.BeanUtils;
/**
* 封装BeanUtils.copyProperties 数组转换
* @param resourcelist 源数组
* @param target 目标对象
* @param <T> 目标对象类型
* @return
*/
public static <T> List<T> copyBeanList(List<?> resourceList, Class<T> target){
List<T> targetList = new LinkedList<>();
if (null==resourceList||resourceList.isEmpty()){
return targetList;
}
resourceList.forEach(e->{
T o = null;
try {
o = target.newInstance();
} catch (InstantiationException | IllegalAccessException ex) {
ex.printStackTrace();
}
BeanUtils.copyProperties(e,o);
objects.add(o);
});
return objects;
}
示例分享
List<A> listA=new ArrayList<>(); List<B> listB=copyBeanList(listA,B.class);
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


