java对象深克隆_Java对象的深拷贝和克隆

在有的时候,我们希望对Java对象执行“深拷贝”。

在Java中,没有提供类似的C++的拷贝构造函数,但是提供了默认的”克隆”接口 Clonable。

如果我们要对一个只包含基础类型(int / long /String)的对象进行克隆,只需要实现Clonable并实现clone()函数即可。

如下:

public class Row implements Cloneable {

long id;

String data;

@Override

public Row clone() throws CloneNotSupportedException {

return (Row) super.clone();

}

}

如果要克隆一个引用了其他对象的Object,就要复杂一些了。

public class Employee implements Cloneable{

private int empoyeeId;

private String employeeName;

private Department department;

public Employee(int id, String name, Department dept)

{

this.empoyeeId = id;

this.employeeName = name;

this.department = dept;

}

//Modified clone() method in Employee class

@Override

protected Employee clone() throws CloneNotSupportedException {

Employee cloned = (Employee)super.clone();

cloned.setDepartment((Department)cloned.getDepartment().clone());

return cloned;

}

//Accessor/mutators methods will go there

}

实际上,还可以通过序列化/反序列化、ApacheCommons的SerializationUtils进行深度拷贝。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值