public static <T> T cloneTo(T src) throws RuntimeException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
T dst = null;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(src);
oos.flush();
ois = new ObjectInputStream(new ByteArrayInputStream(baos
.toByteArray()));
dst = (T) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
throw new RuntimeException();
}
}
oos = null;
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
throw new RuntimeException();
}
}
ois = null;
}
return dst;
}
该方法可以实现深克隆,即不仅克隆对象内部的基本类型,也克隆对象内部的对象。
而与之相对的浅克隆,仅复制对象本身,而对于对象内部的对象则会复制其地址。
注:Boolean对象不会序列化