Teacher.java
package test.clone; /**
* 老师
* 深copy需要实现Cloneable接口
* @author King
*
*/
public class Teacher implements Cloneable { private String name; private int age; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} @Override
public String toString() {
return "Teacher [name=" + name + ", age=" + age + "]";
} public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Student.java
package test.clone; /**
* 学生
* 浅copy需要实现Cloneable接口
* @author King
*
*/
public class Student implements Cloneable { private String name; private int age; private Teacher teacher; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Teacher getTeacher() {
return teacher;
} public void setTeacher(Teacher teacher) {
this.teacher = teacher;
} @Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", Teacher=" + teacher + "]";
} //浅copy
public Object clone() throws CloneNotSupportedException {
return super.clone();
} /**
* 浅copy (同clone()方法)
* 浅copy只对基本类型和String类型做全新复制,
* 属性对象引用是不会全新复制的,最终新copy出来的属性对象引用的还是同一个堆内存区域,比如teacher属性
* @return
* @throws CloneNotSupportedException
* ......
* @time 2018年1月26日 下午8:07:11
* @author King
*/
public Object shallowClone() throws CloneNotSupportedException {
return super.clone();
} /**
* 伪深copy
* 这种伪深copy模式,其实还是使用了浅copy技术,只是把属性对象再次赋了新的浅copy.
* 当对象比较简单时可以用这种模式,因为它比序列化深copy要来得快,还是定制化copy哪些属性
* @return
* @throws CloneNotSupportedException
* ......
* @time 2018年1月26日 下午8:09:39
* @author King
*/
public Object deepClone() throws CloneNotSupportedException {
Student stu = (Student) super.clone();
Teacher t2 = (Teacher) teacher.clone();
stu.setTeacher(t2);
return stu;
} }
FakeDeepCopy.java
伪深copy调用样例
package test.clone; /**
* fakeDeepCopy,其实是一种伪深copy,对象对比简单时可以使用这种技术
*
* @author King
*
*/
public class FakeDeepCopy { public static void main(String[] args) {
Teacher techarAAA = new Teacher();
techarAAA.setName("Teacher AAA");
techarAAA.setAge(30); Student studentAAA = new Student();
studentAAA.setName(new String("Student AAA"));
studentAAA.setAge(15);
studentAAA.setTeacher(techarAAA); System.out.println("学生复制前studentAAA:" + studentAAA);
try {
Student studentCopy = (Student) studentAAA.clone();
Teacher teacherCopy = studentCopy.getTeacher();
studentCopy.setName(new String("Student BBB"));
studentCopy.setAge(20);
teacherCopy.setName("Teacher BBB");
teacherCopy.setAge(45);
studentCopy.setTeacher(teacherCopy);
System.out.println("学生复制后studentAAA:" + studentAAA);
System.out.println("学生复制后studentCopy:" + studentCopy);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
} } }
以上深copy主要通过各层浅copy实现.
真正完整深copy可通过序列化的方式.