2015-04-01 52 views
0

我目前正在嘗試使類具有serialize方法。其目標是在其自己的功能中序列化Singleton。有什麼方法可以在這個類中序列化一個類?類中的類的序列化

這裏是什麼,我嘗試了樣品:

public void serialize() { 
    Singleton commit = this.getInstance(); 

    try { 
     FileOutputStream fileOut = new FileOutputStream(new Config().getDataFile()); 
     ObjectOutputStream out = new ObjectOutputStream(fileOut); 
     out.writeObject(commit); 
     out.close(); 
     fileOut.close(); 
    } catch (Exception e) { 
     System.out.println("Unable to commit database changes."); 
     e.printStackTrace(System.out); 
    } 
} 

和下面的堆棧跟蹤:

Unable to commit database changes. 
java.io.NotSerializableException: com.cuistot.data.Singleton 
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184) 
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348) 
    at [...].Singleton.serialize(Singleton.java:50) 
    [...] 

回答

1

貴類實現Serializable

看着source code forObjectOutputStream.writeObject0,它拋出NotSerializableException如果對象不是Serializable