方法一:
// 方法一
public static <T,K> List<K> convertList1(List<T> sourceList, Class<K> clazz){
List<K> results = new ArrayList<>();
for (T t : sourceList){
K k = JSON.parseObject(JSON.toJSONString(t), clazz);
results.add(k);
}
return results;
}
方法二:
// 方法二
public static <T,K> List<K> convertList2(List<T> sourceList, Class<K> clazz) throws IllegalAccessException, InstantiationException {
List<K> results = new ArrayList<>();
for (T t : sourceList){
K k = clazz.newInstance();
BeanUtils.copyProperties(t, k);
results.add(k);
}
return results;
}
测试方法
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Person person1 = new Person();
person1.setName("foo");
Person person2 = new Person();
person2.setName("bar");
List<Person> personList = new ArrayList<>();
personList.add(person1);
personList.add(person2);
// List<PersonDTO> personDTOList = convertList2(personList, PersonDTO.class);
List<PersonDTO> personDTOList = convertList2(personList, PersonDTO.class);
System.out.println(JSON.toJSONString(personDTOList));
}
测试输出
[{"name":"foo"},{"name":"bar"}]
Process finished with exit code 0
|