前面介绍的是通过实现Cloneable接口并重写Object类的clone()方法来实现克隆。
本节介绍的是通过实现Serializable接口,通过对象的序列化和反序列化实现克隆,即串行化方式实现克隆。
1、为什么需要使用串行化方式实现克隆?
如果引用类型里面还包含很多引用类型,此时使用clone方法就会很麻烦。
此时就需要使用序列化的方式来实现对象的深克隆。
2、串行化
将对象写到流里面的过程称之为串行化过程。
串行化Serilization,在java程序圈子,我们将java序列化的过程称之为“腌咸菜”或“冷冻”
并行化Deserialization,将java反序列化的过程即将对象从流中读出来的过程称之为"回鲜"或“解冻”
那么如何使用串行化来实现深克隆?
先将需要克隆的对象实现Serializable序列化接口
然后将需要克隆的对象写到流里
再从流里读出来,便可以重构对象
实现代码如下:
package com.cn.vo;
import java.io.Serializable;
/**
* 教师实体类
* */
public class TeacherVO implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8018746437851755106L;
private String teacherName; //教师名称
public String getTeacherName() {
return teacherName;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
}
package com.cn.vo;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* 学生实体类
* */
public class Student2VO implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2206290029742876238L;
private String studentName; //学生姓名
private TeacherVO teacher; //所属教师
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public TeacherVO getTeacher() {
return teacher;
}
public void setTeacher(TeacherVO teacher) {
this.teacher = teacher;
}
/**
* 深克隆方法
* @throws IOException
* @throws ClassNotFoundException
* */
public Object deepClone() throws IOException, ClassNotFoundException{
ByteArrayOutputStream bout=new ByteArrayOutputStream();
ObjectOutputStream objectOutput=new ObjectOutputStream(bout);
objectOutput.writeObject(this);
ByteArrayInputStream binput=new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream objectInput=new ObjectInputStream(binput);
return(objectInput.readObject());
}
}
测试
package com.cn.clone;
import java.io.IOException;
import com.cn.vo.Student2VO;
import com.cn.vo.TeacherVO;
public class Test2 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
TeacherVO teacherVO=new TeacherVO();
teacherVO.setTeacherName("lisi");
Student2VO student2vo=new Student2VO();
student2vo.setStudentName("zhangsan");
student2vo.setTeacher(teacherVO);
Student2VO student2vo2=(Student2VO) student2vo.deepClone();
System.out.println(student2vo.getStudentName());
System.out.println(student2vo2.getStudentName());
teacherVO.setTeacherName("wangwu");
System.out.println(student2vo.getStudentName()+"---"+student2vo.getTeacher().getTeacherName());
System.out.println(student2vo2.getStudentName()+"---"+student2vo2.getTeacher().getTeacherName());
}
}
显示结果如下: