1.浅克隆
通过实现Cloneable接口申明Object.clone()方法合法,该默认方法只会对基本类型进行值拷贝,对引用类型进行引用拷贝
package prototypePattern;
/**
* 深拷贝待测试的类
*/
public class Sheep implements Cloneable{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Sheep{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
/**
* 深拷贝测试类
*/
public class Farmer implements Cloneable, Serializable {
private Sheep sheep;
public Sheep getSheep() {
return sheep;
}
public void setSheep(Sheep sheep) {
this.sheep = sheep;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
package prototypePattern;
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Sheep sheep = new Sheep();
sheep.setName("DuoLi");
sheep.setAge(3);
Farmer farmer = new Farmer();
farmer.setSheep(sheep);
Farmer clonedFarmer = (Farmer)farmer.clone();
System.out.println(farmer.getSheep().toString() + farmer.getSheep().hashCode());
System.out.println(clonedFarmer.getSheep().toString() + clonedFarmer.getSheep().hashCode());
}
}
结果:哈希值相同
2.深克隆(同时克隆引用类型)
1. 重写clone方法(对引用类型使用浅拷贝)
@Override
protected Object clone() throws CloneNotSupportedException {
Farmer clone = (Farmer)super.clone();
clone.setSheep((Sheep)this.sheep.clone());
return clone;
}
结果:
2. 序列化(反序列化修改相同则需添加readResolve方法)
public Farmer deepClone(){
Farmer result = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try{
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
result = (Farmer)ois.readObject();
}catch (Exception e){
e.printStackTrace();
}
return result;
}
结果: