添加复制集合中的Bean属性方法,对比原方法(copyToList)减少不常用参数

This commit is contained in:
wangzhen 2021-05-10 14:27:14 +08:00
parent 3cc02ed763
commit 2063cb2453
2 changed files with 45 additions and 0 deletions

View File

@ -734,6 +734,23 @@ public class BeanUtil {
}).collect(Collectors.toList());
}
/**
* 复制集合中的Bean属性<br>
* 此方法遍历集合中每个Bean复制其属性后加入一个新的{@link List}
*
* @param collection 原Bean集合
* @param targetType 目标Bean类型
* @param <T> Bean类型
* @return 复制后的List
*/
public static <T> List<T> copyToList(Collection<?> collection, Class<T> targetType){
return collection.stream().map((source)->{
final T target = ReflectUtil.newInstanceIfPossible(targetType);
copyProperties(source, target);
return target;
}).collect(Collectors.toList());
}
/**
* 给定的Bean的类名是否匹配指定类名字符串<br>
* 如果isSimple为{@code false}则只匹配类名而忽略包名例如cn.hutool.TestEntity只匹配TestEntity<br>

View File

@ -4,8 +4,10 @@ import cn.hutool.core.annotation.Alias;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.bean.copier.ValueProvider;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.Getter;
@ -501,6 +503,12 @@ public class BeanUtilTest {
Assert.assertEquals("{codeList={0={name=张三}}}", resultMap.toString());
}
@Data
public static class Student{
String name;
int age;
Long no;
}
@Test
public void beanCopyTest() {
final Station station = new Station();
@ -512,6 +520,26 @@ public class BeanUtilTest {
Assert.assertEquals(new Long(123456L), station2.getId());
}
@Test
public void copyListTest(){
Student student = ReflectUtil.newInstance(Student.class);
student.setName("张三");
student.setAge(123);
student.setNo(3158L);
Student student2 = ReflectUtil.newInstance(Student.class);
student.setName("李四");
student.setAge(125);
student.setNo(8848L);
List<Student> studentList = ListUtil.of(student, student2);
List<Person> people = BeanUtil.copyToList(studentList, Person.class);
Assert.assertEquals(studentList.size(),people.size());
for (int i = 0; i < studentList.size(); i++) {
Assert.assertEquals(studentList.get(i).getName(),people.get(i).getName());
Assert.assertEquals(studentList.get(i).getAge(),people.get(i).getAge());
}
}
public static class Station extends Tree<Station, Long> {
}