• BeanUtils.copyProperties不能copy复杂对象List的解决方式


    需要注意的就是把List拆分,遍历add,然后把list设置到返回对象中

    package test.test;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.springframework.beans.BeanUtils;
    
    import com.alibaba.fastjson.JSON;
    
    import test.entity.Book;
    import test.entity.Classs;
    import test.entity.Student;
    import test.entity.Teacher;
    
    public class Test {
        public static void main(String[] args) {
            Classs c = new Classs();
            c.setClassName("班级1");
    
            List<Student> sl1 = new ArrayList<>();
            List<Book> bl1 = new ArrayList<>();
            Student s1 = new Student();
            Book b1 = new Book();
            b1.setName("傲慢与偏见");
            b1.setNumber(498);
            bl1.add(b1);
            s1.setBookList(bl1);
            s1.setAddress("龙华民治街道");
            s1.setClassName("班级1");
            s1.setName("小红");
    
            sl1.add(s1);
            c.setStuList(sl1);
    
            List<Teacher> tl1 = new ArrayList<>();
            Teacher t1 = new Teacher();
            t1.setName("张三");
            t1.setAddress("深圳南山");
            tl1.add(t1);
            c.setTeaList(tl1);
    
    //      System.out.println(JSON.toJSON(c));
    
    
            test.entity2.Classs c2 = new test.entity2.Classs();
    
            BeanUtils.copyProperties(c, c2);
    
            List<test.entity2.Student> sl2 = new ArrayList<>();
            for (Student stu1 : sl1) {
                test.entity2.Student stu2 = new test.entity2.Student();
                BeanUtils.copyProperties(stu1, stu2);
    
                List<test.entity2.Book> bl2 = new ArrayList<>();
                for (Book bo1 : stu1.getBookList()) {
                    test.entity2.Book b2 = new test.entity2.Book();
                    BeanUtils.copyProperties(bo1, b2);
    
                    bl2.add(b2);
                }
                stu2.setBookList(bl2);
                sl2.add(stu2);
            }
            c2.setStuList(sl2);
    
            List<test.entity2.Teacher> tl2 = new ArrayList<>();
            for (Teacher tea1 : tl1) {
                test.entity2.Teacher tea2 = new test.entity2.Teacher();
    
                BeanUtils.copyProperties(tea1, tea2);
                tl2.add(tea2);
    
            }
            c2.setTeaList(tl2);
    
    
            System.out.println(JSON.toJSON(c2));
        }
    }
  • 相关阅读:
    linux常用命令
    TP5 使用额外查询
    高性能mysql[day 1]
    tp6 使用多模块/应用
    linux进程间通信的方式
    Mac将本地文件上传到Centos7(Linux)服务器上
    响应式Web设计:构建令人赞叹的Web应用程序的秘诀
    单页应用(SPA,Single-page-App)和多页应用(MPA,Multi-page App)的区别
    PWA(Progressive web apps),渐进式 Web 应用
    10年大佬博客
  • 原文地址:https://www.cnblogs.com/toSeeMyDream/p/7824961.html
Copyright © 2020-2023  润新知