基本思想:把被赋值的主对象写入到一个字节流中,再从字节流中将其读出来,这样就可创建一个新的对象了。且新对象与主对象不存在引用共享。相互独立。
关于Serialization:java通过实现java.io.Serialization接口来启用序列化功能,使用该工具类的对象必须实现Serializable接口,否则无法实现克隆。序列化接口没有方法和字段,无需继承Colneable接口实现clone方法
public class CloneUtil {
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 (Exception e) {
e.printStackTrace();
}
return cloneObj;
}
}
。