java的clone有两种方式:
1). 实现Cloneable接口并重写clone()方法,也可以实现深度克隆;
参看:https://www.cnblogs.com/acode/p/6306887.html
2). 实现Serializable接口,通过对象的序列化和反序列化实现克隆,可以实现真正的深度克隆。
参看:https://blog.csdn.net/HD243608836/article/details/79955595的“29、如何实现对象克隆?”
针对第二种方式(Serializable)的步骤详细说明:
//注意:“obj参数”必须实现Serializable接口
public static <T> T clone(T obj) throws IOException, ClassNotFoundException{
//第一步(输出):save the object to a byte array
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bout);
oos.writeObject(obj);
//PS:内存流不用关闭(关闭也没用,还可以继续调用),对象流或文件流则需要关闭
oos.close();
//第二步(读入):read a clone of the object from byte array
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bin);
T ret = (T) ois.readObject();
ois.close();
return ret;
}