使用序列化的方式,在内存中拷贝对象。将母对象写入到一个字节流中,将母对象写入到一个字节流,再从字节流中读取该对象。这样新的对象与母对象之间并不存在引用共享问题,从而实现对象的深拷贝。
这种实现深拷贝的方式对工程上也有好处:只需要写个工具类,其他对象如果想拷贝的话,可以直接使用这个工具类。
public class DeepCloneUtils {
/**
* 通过序列化的方式实现深拷贝
*
* @param obj 需要拷贝的母对象
* @param <T> 母对象的类型,要求其实现了Serializable接口
* @return
*/
@SuppressWarnings("unchecked")
public static <T extends Serializable> T clone(T obj){
T cloneObj = null;
try {
// 将母对象写入字节流
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream obs = new ObjectOutputStream(out);
obs.writeObject(obj);
obs.close();
// 分配内存,写入原始对象,生成新的对象
ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray());
ObjectInputStream ois = new ObjectInputStream(ios);
// 得到新的对象
cloneObj = (T)ois.readObject();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return cloneObj;
}
}
测试一下:
public class Person implements Serializable {
private int id;
private String name;
private Date birthday;
// 省略get、set方法;构造方法
public static void main(String[] args) {
Person person = new Person(1, "王杰", new Date(19, 8, 23));
Person clone = DeepCloneUtils.clone(person);
System.out.println(clone);
}
}