Clone Object

1.         克隆有三种方法:

1)        实现Cloneable接口,重写他的clone()方法。

 

@Override
protected Object clone() throws CloneNotSupportedException {
	return super.clone();
}

 2)        使用BeanUtils类的方法。

    a)         BeanUtils.copyProperties(desObject, srcObject);将源对像srcObject克隆一分给desObject

        b)        BeanUtils.cloneBean(object);克隆一个对像

        以上1)和2)两种方法都只能是浅层克隆,也就是说对像里存在对像时子对像不会被克隆。

 3)        对像序列化,不管主类中嵌套有多深,都可以实现深层拷贝:

 

public static Object clone(Object obj) throws Exception {
	ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
	ObjectOutputStream outStream = new ObjectOutputStream(byteOut);
	outStream.writeObject(obj);
	ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
	ObjectInputStream inStream = new ObjectInputStream(byteIn);
	return inStream.readObject();
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值