原文鏈接:https://blog.csdn.net/weixin_39792935/article/details/85703570
最近在做項目時,遇到一個java深拷貝的問題汗茄,常見有兩種方式:
實現(xiàn)Cloneable接口踩蔚,并且重寫Object類中的clone()方法
實現(xiàn)Serializable接口序列化
詳情請移步:Java對象-深拷貝(實現(xiàn)Serializable, Cloneable兩種方式)
publicclassDemoimplementsCloneable{
privateString name;
privateString value;
privateDemoInternal demoInternal;
/*省略getter和setter方法*/
@Override
publicDemoclone(){
Demo demo =null;
try{
demo = (Demo)super.clone();//淺復(fù)制
}catch(CloneNotSupportedException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
demo.demoInternal = demoInternal.clone();//深度復(fù)制
returndemo;
? ? }
}
publicclassDemoInternalimplementsCloneable{
privateString internalName;
privateString internalValue;
/*省略getter和setter方法*/
@Override
publicDemoInternalclone(){
DemoInternal demoInternal =null;
try{
demoInternal = (DemoInternal)super.clone();
}catch(CloneNotSupportedException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
returndemoInternal;
? ? }
}
importjava.io.ByteArrayInputStream;
importjava.io.ByteArrayOutputStream;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;
importjava.io.Serializable;
/**
* 通過字節(jié)流序列化實現(xiàn)深拷貝盔夜,需要深拷貝的對象必須實現(xiàn)Serializable接口
*
*@authorAdministrator
*/
publicclassCloneUtils{
@SuppressWarnings("unchecked")
publicstaticTclone(T obj){
T cloneObj =null;
try{
// 寫入字節(jié)流
ByteArrayOutputStream out =newByteArrayOutputStream();
ObjectOutputStream obs =newObjectOutputStream(out);
obs.writeObject(obj);
obs.close();
// 分配內(nèi)存,寫入原始對象,生成新對象
ByteArrayInputStream ios =newByteArrayInputStream(out.toByteArray());
ObjectInputStream ois =newObjectInputStream(ios);
// 返回生成的新對象
cloneObj = (T) ois.readObject();
ois.close();
}catch(Exception e) {
e.printStackTrace();
}
returncloneObj;
}
}
上述的兩種方式灵奖,都是通過一層又一層地深入容握,實現(xiàn)對象的深度復(fù)制宣脉。所以,如果您遇到類似于下面的問題時:
我已經(jīng)實現(xiàn)了java.io.Serializable的接口了剔氏,為什么還提示我NotSerializableException塑猖?
不要迷惑堪遂,一定是您忘記將某一個類實現(xiàn)Serializable接口,排錯的方法是萌庆,使用try catch捕獲異常溶褪,e.getMessage會打印出您忘記實現(xiàn)Serializable接口的類名,將該類實現(xiàn)Serializable接口即可践险。