对象的深复制方法(对象流实现)

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);
	}

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值