将对象集合转换成另外一个对象集合
不能通过类型参数创建对象。例如T t = new T();
public class ListUtil {
public static <S, T> List<T> copyProperties(List<S> sources, Supplier<T> target) {
return sources.stream().map(source -> {
T t = target.get();
BeanUtils.copyProperties(source, t);
return t;
}).collect(Collectors.toList());
}
public static <S, T> List<T> copyListProperties(List<S> sources, Class<T> target) {
return sources.stream().map(source -> {
T t;
try {
t = target.newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}
BeanUtils.copyProperties(source, t);
return t;
}).collect(Collectors.toList());
}
}
public static void main(String[] args) {
List<User> users= Arrays.asList(
new User(1,"麻子"),
new User(2,"张三"),
new User(3,"李四"),
new User(4,"王五")
);
List<UserDTO> userDTOS= ListUtil .copyProperties(users, UserDTO::new);
userDTOS.forEach(System.out::println);
System.out.println("=======================================================");
List<UserDTO> userDTOS2= ColaBeanUtils.copyListProperties(users, UserDTO.class);
userDTOS2.forEach(System.out::println);
}