类中的类的序列化

时间:2015-04-01 15:22:29

标签: java serialization deserialization

我目前正在尝试使用Singleton方法制作课程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 个答案:

答案 0 :(得分:1)

您的班级是否实施了Serializable

查看source code for ObjectOutputStream.writeObject0,如果对象不是NotSerializableException,则会抛出Serializable