因爲項目裏面自定義的類裏面嵌套太多複雜自定義對象,挨個實現clone接口太麻煩,還涉及到hasMap的深拷貝,
剛開始使用gson或者fastjson的序列化,反序列化的方式進行深拷貝,但是一直報錯,
Gson報錯:java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: ...TextView. Forgot to register a type adapter?
fastJson報錯:JavaBean error
Google很久試了幾個方法都沒解決。
最後通過下面這個,直接通過輸入輸出流序列化的方式深拷貝的對象:
來源:https://www.jianshu.com/p/eb2113e12ecb
/**
* 對象深度複製(對象必須是實現了Serializable接口)
*/
@SuppressWarnings("unchecked")
public static <T extends Serializable> T clone(T obj) {
T clonedObj = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
clonedObj = (T) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
return clonedObj;
}