首先介绍下对象的深克隆与浅克隆
/**
* 深克隆与浅克隆 :
*
* 1>相同点
* 深克隆与浅克隆都会把之前的基本类型的数据完全克隆
* 被克隆出来的对象更改自己的基本类型数据后不会影响原生的对象
*
* 2>不同点
* 浅克隆出来的对象它自身的引用类型的属性仍然指向原来的对象。
* 被克隆的对象修改引用类型的属性值后,原生的对象也会修改
*
* 深克隆出来的对象它自身的引用类型的属性不会指向原来的对象。
* 被克隆的对象修改引用类型的属性值后,原生的对象不会被修改
*/
/**
* 注:
*
* 1>要实现深克隆与浅克隆,对象必须实现Cloneable接口
*
* 2>本文中要实现深克隆,对象和对象中的引用对象要实现Serializable接口,
* (因为本文中的深克隆是依靠序列化实现的)
*/
下面我们分别为深克隆与浅克隆举例
首先是JavaBean
public class Teacher implements Serializable {
private static final long serialVersionUID = 1L;
public String name;
public int age;
public Teacher() {
super();
}
public Teacher(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
public class Student implements Cloneable, Serializable {
private static final long serialVersionUID = 1L;
public String name;
public int age;
public Teacher teacher;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student(String name, int age, Teacher teacher) {
super();
this.name = name;
this.age = age;
this.teacher = teacher;
}
/**
* 浅复制
*/
public Object clone() {
Object o = null;
try {
// Object 中的clone()识别出你要复制的是哪一个对象。
o = (Student) super.clone();
} catch (CloneNotSupportedException e) {
System.out.println(e.toString());
}
return o;
}
/**
* 深复制
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
public Object deepClone() throws IOException, ClassNotFoundException {
/* 写入当前对象的二进制流 */
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
/* 读出二进制流产生的新对象 */
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return ois.readObject();
}
}
/**
* 浅克隆
*/
public static void test1 (){
Teacher teacher = new Teacher("季老师",35);
Student student = new Student("张三",20,teacher);
Student stuClone = (Student) student.clone();
stuClone.name = "李四";
stuClone.age = 22;
stuClone.teacher.name = "王老师";
stuClone.teacher.age = 40;
/************************/
//张三---20
System.out.println(student.name+"---"+student.age);
//李四---22
System.out.println(stuClone.name+"---"+stuClone.age);
//王老师---40
System.out.println(student.teacher.name+"---"+student.teacher.age);
//王老师---40
System.out.println(stuClone.teacher.name+"---"+stuClone.teacher.age);
}
/**
* 深克隆
* @throws IOException
* @throws ClassNotFoundException
*/
public static void test2 () throws ClassNotFoundException, IOException{
Teacher teacher = new Teacher("季老师",35);
Student student = new Student("张三",20,teacher);
Student stuClone = (Student) student.deepClone();
stuClone.name = "李四";
stuClone.age = 22;
stuClone.teacher.name = "王老师";
stuClone.teacher.age = 40;
/************************/
//张三---20
System.out.println(student.name+"---"+student.age);
//李四---22
System.out.println(stuClone.name+"---"+stuClone.age);
//季老师---35
System.out.println(student.teacher.name+"---"+student.teacher.age);
//王老师---40
System.out.println(stuClone.teacher.name+"---"+stuClone.teacher.age);
}