BeanUtils.copyProperties()无法复制List<entiy>集合,制作通用工具类来解决。

BeanUtils.copyProperties()无法复制List集合,制作通用工具类来解决。


1. 需求分析

  1. BeanUtils.copyProperties(source,target),用于把source实体的属性值复制给target实体(同名属性可复制
  2. 当需要对List进行整体复制到另一个List时,此方法达不到预期。
  3. 查了网上资料,大多推荐使用循坏对entiy遍历进行BeanUtils.copyProperties操作。
  4. 单一对entiy的循环,降低了复用性,个人不喜欢。
  5. 利用反射的机制,做一个复用性强一些的工具类,实现对List对不同的class的复制。

2. 两个实体类

@Data
public class Student {

    private int id;
    private String name;
    private int age;

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
public class StudentBoss {

    private int id;
    private String name;
    private int age;
    private String address;

}

3. 反射转换

 public <T> List<T> exchange(List<?> source, Class<T> clz) throws Exception {
        List<T> res = new ArrayList<>();
        for (Object o : source) {
            T t = clz.getConstructor().newInstance();  //实例化
            BeanUtils.copyProperties(o,t);    //复制同名属性值
            res.add(t);
        }
        return res;
    }

4. 测试代码

    @Test
    public void copyproperties() throws Exception {
        List<Student> stu = new ArrayList<>();
        stu.add(new Student(1, "小明", 12));
        stu.add(new Student(2, "小明1", 13));
        System.out.println("student=>"+stu);
        List<StudentBoss> exchange = exchange(stu, StudentBoss.class);
        System.out.println("studentBoos=>"+exchange);
    }

5. 测试结果

BeanUtils.copyProperties()无法复制List<entiy>集合,制作通用工具类来解决。_第1张图片

6. 总结

平时多思考复用性,在开发中可以有效提升开发效率,同时也可以提升自身对面向对象的理解。坚持对反射内容的研究。学无止境

你可能感兴趣的:(spring,boot,工作记录,list,java,反射,泛型)