JAVA复制对象和集合的工具类
因为BeanUtils.copyProperties(Object source, Object target),只能复制对象,不能复制数组和集合,所以决定写个工具类来解决
public class CopyUtils {
/**
* 复制对象
*/
public static <T,K> T convert(K source, Class<T> clazz) {
T t = BeanUtils.instantiate(clazz);
BeanUtils.copyProperties(source, t);
return t;
}
/**
* 复制集合
*/
public static <T,K> List<T> copyList(List<K> sourceList, Class<T> clazz) {
if (CollectionUtils.isEmpty(sourceList)) {
return null;
}
return Lists2.transform(sourceList,input -> convert(input, clazz));
}
}
写个单元测试来测试
@Test
public void copy(){
WarehouseEntity warehouseEntity = WarehouseEntity.builder().id(1).name("仓库1").build();
WarehouseDTO warehouseDTO = CopyUtils.convert(warehouseEntity, WarehouseDTO.class);
log.info(JSONObject.toJSONString(warehouseDTO));
ArrayList<WarehouseEntity> warehouseEntities = Lists.newArrayList(warehouseEntity);
List<WarehouseDTO> warehouseDTOS = CopyUtils.copyList(warehouseEntities, WarehouseDTO.class);
log.info(JSONObject.toJSONString(warehouseDTOS));
}
结果
{"id":1,"name":"仓库1"}
[{"id":1,"name":"仓库1"}]