淺複製:實現cloneable接口,適用於類成員是值的情況。如果類成員是對象,那麼此成員對象類也必須實現複製過程。否則不能實現成員類對象的複製。
深複製:內存複製,兩種方法:
1. 自己寫代碼,以前就這麼幹的。。
public static <T> T deepCopy(T src) throws IOException, ClassNotFoundException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(src);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
@SuppressWarnings("unchecked")
T dest = (T) in.readObject();
return dest;
}
2.直接使用工具類
org.apache.commons.lang3.SerializationUtils
具體實現過程看源碼吧。
不是代碼不好寫,是因爲我們不知道還有捷徑ORZ..