1 深拷贝,浅拷贝
浅拷贝:对基本数据类型进行值传递,对引用数据类型进行引用传递般的拷贝,此为浅拷贝。
深拷贝:对基本数据类型进行值传递,对引用数据类型,创建一个新的对象,并复制其内容,此为深拷贝。
2 BeanUtils.copyProperties
注意:避免使用Apache Beanutils进行属性copy。因为Apache Beanutils性能较差,可以使用其他方案如:Spring BeanUtils,Cglib BeanCopier,注意均是浅拷贝。
其实常见的BeanUtils有2个: spring有BeanUtils apache的commons也有BeanUtils。
接下来用代码验证上述结论:
两个实体类:
实体类Student
@Data
public class Student {
private String stuName;
private Integer age;
}
实体类People
@Data
public class People {
private String name;
private Student student;
}
测试代码:
public static void main(String[] args) {
People people = new People();
people.setName("阿三");
Student student = new Student();
student.setStuName("李四");
student.setAge(20);
people.setStudent(student);
People people1 = new People();
/**
* 将people中的属性拷贝给people1
*/
BeanUtils.copyProperties(people,people1);
System.out.println("people中的student属性:"+JSON.toJSONString(people.getStudent()));
System.out.println("people1中的student属性:"+JSON.toJSONString(people1.getStudent()));
/**
* 查看people中和people1的引用数据类型是否是同一个以此来判断BeanUtils.copyProperties(source,target)是深拷贝还是浅拷贝
*/
System.out.println(people.getStudent() == people1.getStudent()); //true 引用地址一样说明其是浅拷贝
/**
* 修改拷贝后的数据看是否会对源对象会有影响
*/
people1.getStudent().setAge(123456);
System.out.println("修改后people中的student属性:"+JSON.toJSONString(people.getStudent()));
System.out.println("修改后people1中的student属性:"+JSON.toJSONString(people1.getStudent()));
}
测试结果:
如果想要将外部类的属性直接复制给内部类,是复制不上的。
People people = new People();
people.setName("阿三");
Student student = new Student();
student.setStuName("李四");
student.setAge(20);
people.setStudent(student);
Student student1 = new Student();
/**
* 将people中的属性拷贝给people1
*/
BeanUtils.copyProperties(people,student1);
System.out.println(JSON.toJSONString(student1));
BeanUtils.copyProperties(people.getStudent(),student1);
System.out.println(JSON.toJSONString(student1));
?测试结果:
?
|