Java对象的深拷贝和克隆

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

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

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

如下:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public class Row implements Cloneable {
long id;
String data;
@Override
public Row clone() throws CloneNotSupportedException {
return (Row) super.clone();
}
}
public class Row implements Cloneable { long id; String data; @Override public Row clone() throws CloneNotSupportedException { return (Row) super.clone(); } }
	public class Row implements Cloneable {

		long id;
		String data;

		@Override
		public Row clone() throws CloneNotSupportedException {
			return (Row) super.clone();
		}
	}

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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
}
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 }
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进行深度拷贝。

参考文献:A guide to object cloning in java

 

Leave a Reply

Your email address will not be published. Required fields are marked *