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)); } }
posted on 2017-11-13 09:49 nickTimer 阅读(22327) 评论(1) 编辑 收藏 举报