JAVA 有两种深度复制实现方式,分别是实现Cloneabel接口,并在接口函数中为每个属性调用Cloneable,也可以通过序列化的方式来实现。
package JAVAImprove;
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 DeepClone implements Cloneable, Serializable{
private transient LearnClone Lc;
public LearnClone getLc() {
return Lc;
}
public void setLc(LearnClone lc) {
Lc = lc;
}
//注意序列化是不会调用构造函数的。
public DeepClone(){
System.out.println("Constractor");
Lc = new LearnClone();
}
public static void main(String[] args){
DeepClone dc = new DeepClone();
try {
DeepClone dc2 = (DeepClone)dc.clone();
System.out.println("dc start:" + dc.getLc().getCheck());
System.out.println("dc2 start:" + dc2.getLc().getCheck());
//深度复制
ByteArrayOutputStream bo = new ByteArrayOutputStream();
try {
ObjectOutputStream ot = new ObjectOutputStream(bo);
ot.writeObject(dc);
ot.close();
ByteArrayInputStream io = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream ip = new ObjectInputStream(io);
//try {
DeepClone dc3 = (DeepClone)ip.readObject();
dc3.getLc().setCheck("is Deep Clone");
System.out.println("dc3 end" + dc3.getLc().getCheck());
System.out.println("dc end" + dc.getLc().getCheck());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package JAVAImprove;
import java.io.Serializable;
public class LearnClone implements Cloneable, Serializable {
private String check = "learn Clone";
public String getCheck() {
return check;
}
public void setCheck(String check) {
this.check = check;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args){
//
LearnClone cl = new LearnClone();
cl.setCheck("ttt");
LearnClone c2;
try {
c2 = (LearnClone)cl.clone();
if(c2 == cl){
System.out.println("equal");//首先实现接口可以完成属性的拷贝。
}
System.out.println("start cl" + cl.getCheck());
System.out.println("start c2" + c2.getCheck());
//不是一个值
c2.setCheck("aaaaaaaaaaaaaa");
System.out.println("c2" + c2.getCheck());
System.out.println("C1" + cl.getCheck());
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}