1.深复制地址发生变化:
对象流.A@3ec44cfb
对象流.A@3a087286
2.深复制内容互不影响:
修改前:
a1:
A [a=a1:a, b=a1:b]
a2:
A [a=a1:a, b=a1:b]
修改a2后:
a1:
A [a=a1:a, b=a1:b]
a2:
A [a=a2:a, b=a2:b]
3.代码:
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 A implements Serializable{
private static final long serialVersionUID = -1014177980100080980L;
private String a;
private String b;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
@Override
public String toString() {
return "A [a=" + a + ", b=" + b + "]";
}
/**
* 深复制
* @return
*/
public Object deepClone(){
ByteArrayOutputStream bo=null;
ObjectOutputStream oo=null;
ByteArrayInputStream bi=null;
ObjectInputStream oi=null;
Object object=null;
try {
bo=new ByteArrayOutputStream();
oo=new ObjectOutputStream(bo);
oo.writeObject(this);
bi=new ByteArrayInputStream(bo.toByteArray());
oi=new ObjectInputStream(bi);
object=oi.readObject();
} catch (Exception e) {
e.printStackTrace();
}finally {
if(bo!=null){
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(oo!=null){
try {
oo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bi!=null){
try {
bi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(oi!=null){
try {
oi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return object;
}
public static void main(String[] args) throws CloneNotSupportedException {
A a1=new A();
a1.setA("a1:a");
a1.setB("a1:b");
System.out.println(a1);
A a2=(A)a1.deepClone();
System.out.println(a2);
a2.setA("a2:a");
a2.setB("a2:b");
System.out.println(a1);
System.out.println(a2);
}
}