首页 > java > java如何实现对象的克隆

java如何实现对象的克隆

作者:bin

java克隆有2种方式,使用clone方法去克隆,或者使用序列化的方式进行克隆

1.使用clone方法进行克隆
需要实现Cloneable接口,并且实现他的clone方法,方法中调用super的clone方法生成一个新的对象返回

class Student implements Cloneable{  
    @Override  
    public Object clone() {  
        Student stu = null;  
        try{  
            stu = (Student)super.clone();  
        }catch(CloneNotSupportedException e) {  
            e.printStackTrace();  
        }  
        return stu;  
    }  
}   

深度克隆:指的是不仅仅克隆当前对象,还要克隆当前对象的属性的引用对象。

class Student implements Cloneable{  
    
    //这里引用的mother
    private Mother mother;
    
    @Override  
    public Object clone() {  
        Student stu = null;  
        try{  
            //这里是浅拷贝
            stu = (Student)super.clone();  
        }catch(CloneNotSupportedException e) {  
            e.printStackTrace();  
        }  
        //拷贝他的引用,完成深度拷贝
        stu.mother =  (Mother)mother.clone();
        return stu;  
    }  
}   

2.使用serializable接口
序列化时会生成一个对象的拷贝副本,并且原对象还在内存中,再进行反序列化拷贝对象。

public class Outer implements Serializable{
   private static final long serialVersionUID = 31243123172941L;  //最好是显式声明ID
   public Inner inner;
  //Discription:[深度复制方法,需要对象及对象所有的对象属性都实现序列化] 
   public Outer myclone() {
    Outer outer = null;
    try { 
      // 将该对象序列化成流,因为写在流里的是对象的一个拷贝,而原对象仍然存在于JVM里面。所以利用这个特性可以实现对象的深拷贝
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          ObjectOutputStream oos = new ObjectOutputStream(baos);
          oos.writeObject(this);
       // 将流序列化成对象
          ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
          ObjectInputStream ois = new ObjectInputStream(bais);
          outer = (Outer) ois.readObject();
    } catch (IOException e) {
          e.printStackTrace();
    } catch (ClassNotFoundException e) {
          e.printStackTrace();
    }
    //返回克隆后的对象
    return outer;
 }
}

序列化克隆本质就是深度克隆,但是引用的属性也要继承Serializable接口

public class Outer implements Inner{
...
}

您必须 [ 登录 ] 才能发表留言!