以下文字转自:桔子园 http://www.blogjava.net/orangelizq/archive/2007/10/17/153573.html
现在Clone已经不是一个新鲜词语了,伴随着“多莉”的产生这个词语确实很“火”过一阵子,在java中也有这么一个概念,它可以让我们很方便的“制造”出一个对象的副本来,下面来具体看看java中的Clone机制是如何工作的?
1. Clone&Copy
假设现在有一个Employee对象,Employee tobby =new Employee(“CMTobby”,5000),通
常我们会有这样的赋值Employee cindyelf=tobby,这个时候只是简单了copy了一下reference,cindyelf和tobby都指向内存中同一个object,这样cindyelf或者tobby的一个操作都可能影响到对方。打个比方,如果我们通过cindyelf.raiseSalary()方法改变了salary域的值,那么tobby通过getSalary()方法得到的就是修改之后的salary域的值,显然这不是我们愿意看到的。我们希望得到tobby的一个精确拷贝,同时两者互不影响,这时候我们就可以使用Clone来满足我们的需求。Employee cindy=tobby.clone(),这时会生成一个新的Employee对象,并且和tobby具有相同的属性值和方法。
2. Shallow Clone&Deep Clone
Clone是如何完成的呢?Object在对某个对象实施Clone时对其是一无所知的,它仅仅是简单地执行域对域的copy,这就是Shallow Clone。这样,问题就来了咯,以Employee为例,它里面有一个域hireDay不是基本型别的变量,而是一个reference变量,经过Clone之后就会产生一个新的Date型别的reference,它和原始对象中对应的域指向同一个Date对象,这样克隆类就和原始类共享了一部分信息,而这样显然是不利的,过程下图所示:
这个时候我们就需要进行deep Clone了,对那些非基本型别的域进行特殊的处理,例如本例中的hireDay。我们可以重新定义Clone方法,对hireDay做特殊处理,如下代码所示:
- class Employee implements Cloneable
- {
- public Object clone() throws CloneNotSupportedException
- {
- Employee cloned = (Employee) super.clone();
- cloned.hireDay = (Date) hireDay.clone()
- return cloned;
- }
- }
3. Clone()方法的保护机制
在Object中Clone()是被申明为protected的,这样做是有一定的道理的,以Employee
类为例,通过申明为protected,就可以保证只有Employee类里面才能“克隆”Employee对象,原理可以参考我前面关于public、protected、private的学习笔记。
4. Clone()方法的使用
Clone()方法的使用比较简单,注意如下几点即可:
a. 什么时候使用shallow Clone,什么时候使用deep Clone,这个主要看具体对象的域是什么性质的,基本型别还是reference variable
b. 调用Clone()方法的对象所属的类(Class)必须implements Clonable接口,否则在调用Clone方法的时候会抛出CloneNotSupportedException。
1.java里的clone分为:
A:浅复制(浅克隆): 浅复制仅仅复制所考虑的对象,而不复制它所引用的对象。
b:深复制(深克隆):深复制把要复制的对象所引用的对象都复制了一遍。
Java中对象的克隆,为了获取对象的一份拷贝,我们可以利用Object类的clone()方法。必须要遵循下面三点
1.在派生类中覆盖基类的clone()方法,并声明为public【Object类中的clone()方法为protected的】。
2.在派生类的clone()方法中,调用super.clone()。
3.在派生类中实现Cloneable接口。
Object类里的clone方法是浅复制(浅克隆)
浅复制(浅克隆)的例子如下:
- package com.test;
- //浅复制(浅克隆): 浅复制仅仅复制所考虑的对象,而不复制它所引用的对象。
- //深复制(深克隆):深复制把要复制的对象所引用的对象都复制了一遍。
- //
- //Java中对象的克隆,为了获取对象的一份拷贝,我们可以利用Object类的clone()方法。必须要遵循下面三点
- //1.在派生类中覆盖基类的clone()方法,并声明为public【Object类中的clone()方法为protected的】。
- //2.在派生类的clone()方法中,调用super.clone()。
- //3.在派生类中实现Cloneable接口。
- //[color=red]Object类里的clone方法是浅复制(浅克隆)[/color]public class CloneTest {
- public static void main(String[] args) throws Exception{
- //teacher对象将被clone出来的Student对象共享.
- Teacher teacher = new Teacher();
- teacher.setAge(40);
- teacher.setName("Teacher zhang");
- Student student1 = new Student();
- student1.setAge(20);
- student1.setName("zhangsan");
- student1.setTeacher(teacher);
- //复制出来一个对象student2
- Student student2 = (Student)student1.clone();
- System.out.println(student2.getAge());
- System.out.println(student2.getName());
- System.out.println("~~~~~~~~~~~~~~~~~~~~~~");
- System.out.println(student1.getTeacher().getAge());
- System.out.println(student1.getTeacher().getName());
- //修改student2的引用对象
- student2.getTeacher().setAge(50);
- student2.getTeacher().setName("Teacher Li");
- System.out.println("~~~~~~~~~~~~~~~~~~~~~~");
- System.out.println(student1.getTeacher().getAge());
- System.out.println(student1.getTeacher().getName());
- }
- }
- class Teacher {
- public int age;
- public String name;
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
- class Student implements Cloneable{
- public int age ;
- public String name;
- public Teacher teacher;
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Teacher getTeacher() {
- return teacher;
- }
- public void setTeacher(Teacher teacher) {
- this.teacher = teacher;
- }
- @Override
- public Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
- }
- 输出结果为:
- 20
- zhangsan
- ~~~~~~~~~~~~~~~~~~~~~~
- 40
- Teacher zhang
- ~~~~~~~~~~~~~~~~~~~~~~
- 50
- Teacher Li
2.深复制(深Clone)例子:
- package com.test1;
- //深clone
- public class DeepCloneTest {
- public static void main(String[] args) throws Exception{
- //teacher对象将不被clone出来的Student对象共享.
- Teacher teacher = new Teacher();
- teacher.setAge(40);
- teacher.setName("Teacher zhang");
- Student student1 = new Student();
- student1.setAge(20);
- student1.setName("zhangsan");
- student1.setTeacher(teacher);
- //复制出来一个对象student2
- Student student2 = (Student)student1.clone();
- System.out.println(student2.getAge());
- System.out.println(student2.getName());
- System.out.println("~~~~~~~~~~~~~~~~~~~~~~");
- System.out.println(student1.getTeacher().getAge());
- System.out.println(student1.getTeacher().getName());
- //修改student2的引用对象
- student2.getTeacher().setAge(50);
- student2.getTeacher().setName("Teacher Li");
- System.out.println("~~~~~~~~~~~~~~~~~~~~~~");
- System.out.println(student1.getTeacher().getAge());
- System.out.println(student1.getTeacher().getName());
- }
- }
- class Teacher implements Cloneable{
- public int age;
- public String name;
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- @Override
- public Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
- }
- class Student implements Cloneable{
- public int age ;
- public String name;
- public Teacher teacher;
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Teacher getTeacher() {
- return teacher;
- }
- public void setTeacher(Teacher teacher) {
- this.teacher = teacher;
- }
- @Override
- public Object clone() throws CloneNotSupportedException {
- Student student = (Student)super.clone();
- //将引用的对象teacher也clone下
- student.setTeacher((Teacher)(student.getTeacher().clone()));
- return student;
- }
- }
- 输出结果为:
- 20
- zhangsan
- ~~~~~~~~~~~~~~~~~~~~~~
- 40
- Teacher zhang
- ~~~~~~~~~~~~~~~~~~~~~~
- 40
- Teacher zhang
3.利用序列化来做深复制,把对象写到流里的过程是序列化(Serilization)过程,而把对象从流中读出来的过程则叫做反序列化(Deserialization)过程。应当指出的是, 写在流里的是对象的一个拷贝,而原对象仍然存在于JVM里面。 ,利用这个特性,可以做深拷贝
- package com.test3;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.io.Serializable;
- //利用序列化来做深复制
- //深clone
- public class DeepCloneTest {
- public static void main(String[] args) throws Exception{
- //teacher对象将不被clone出来的Student对象共享.
- Teacher teacher = new Teacher();
- teacher.setAge(40);
- teacher.setName("Teacher zhang");
- Student student1 = new Student();
- student1.setAge(20);
- student1.setName("zhangsan");
- student1.setTeacher(teacher);
- //复制出来一个对象student2
- Student student2 = (Student)student1.deepCopy();
- System.out.println(student2.getAge());
- System.out.println(student2.getName());
- System.out.println("~~~~~~~~~~~~~~~~~~~~~~");
- System.out.println(student1.getTeacher().getAge());
- System.out.println(student1.getTeacher().getName());
- //修改student2的引用对象
- student2.getTeacher().setAge(50);
- student2.getTeacher().setName("Teacher Li");
- System.out.println("~~~~~~~~~~~~~~~~~~~~~~");
- System.out.println(student1.getTeacher().getAge());
- System.out.println(student1.getTeacher().getName());
- }
- }
- class Teacher implements Serializable{
- private static final long serialVersionUID = -8834559347461591191L;
- public int age;
- public String name;
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
- class Student implements Serializable{
- //serialVersionUID 如果你的对象序列化后存到硬盘上面后,可是后来你却更改了类的field(增加或减少或改名),当你反序列化时,就会出现Exception的,这样就会造成不兼容性的问题。
- //但当serialVersionUID相同时,它就会将不一样的field以type的缺省值赋值(如int型的是0,String型的是null等),这个可以避开不兼容性的问题。所以最好给serialVersionUID赋值
- private static final long serialVersionUID = 7991552226614088458L;
- public int age ;
- public String name;
- public Teacher teacher;
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Teacher getTeacher() {
- return teacher;
- }
- public void setTeacher(Teacher teacher) {
- this.teacher = teacher;
- }
- public Object deepCopy() throws Exception{
- //将该对象序列化成流,因为写在流里的是对象的一个拷贝,而原对象仍然存在于JVM里面。所以利用这个特性可以实现对象的深拷贝
- 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();
- }
- }
- 输出结果为:
- 20
- zhangsan
- ~~~~~~~~~~~~~~~~~~~~~~
- 40
- Teacher zhang
- ~~~~~~~~~~~~~~~~~~~~~~
- 40
- Teacher zhang