JAVA深克隆
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* @author wangyong
*
*/
public class FormTest {
public static Object objectCopy(Object sourceObj) //throws CloneNotSupportedException
{
//实现深克隆(即深复制)
try
{
//将对象写到流里
ByteArrayOutputStream bo=new ByteArrayOutputStream();
ObjectOutputStream oo=new ObjectOutputStream(bo);
oo.writeObject(sourceObj);//源对象
//从流里读出来
ByteArrayInputStream bi=new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi=new ObjectInputStream(bi);
return(oi.readObject());//目标对象
}
catch(Exception ex)
{
ex.printStackTrace();
return null;
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
try
{
B b1 = new B();
b1.sb="b1";
B b2 = new B();
b2.sb="b2";
A a1 = new A(b1);
A a2 = new A(b2);
a1.s="wy";
a1.o="obj a1";
a2=(A)a1.clone();//或 objectCopy(a1);
//a2.b.sb="456";
a2.s="a2";
a2.b.sb="new b2";
a2.o="obj a2";
String ss = a2.s;
//实现深复制之后, a1 中的对象 b 不会受到 a2 的重新赋值而改变;
}
catch(Exception ex)
{
ex.printStackTrace();
ex.getMessage();
}
//说明:要序列化的类需要实现 Serializable 接口;
//要克隆的类需要实现 Cloneable 接口;
}
}
class A implements Cloneable,Serializable
{
public String s = null;
public Object o = null;
public B b=null;
A(B bb)
{
b = new B();
b.sb=bb.sb;
}
public Object clone() //throws CloneNotSupportedException
{
try
{
/*//浅克隆(即浅复制)
A a = (A) super.clone();
return a;*/
//实现深克隆(即深复制)
//将对象写到流里
ByteArrayOutputStream bo=new ByteArrayOutputStream();
ObjectOutputStream oo=new ObjectOutputStream(bo);
oo.writeObject(this);//序列化当前类
//从流里读出来
ByteArrayInputStream bi=new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi=new ObjectInputStream(bi);
return(oi.readObject());
}
catch(Exception ex)
{
ex.printStackTrace();
return null;
}
}
}
class B implements Serializable
{
String sb = null;
}