我有一个类类似于以下基本示例的程序:

public class Vertex extends Circle implements Serializable {
    private int vertexID;
    private final static double SIZE = 10.0;

    // Constructor
    public Vertex(int ID, double x, double y) {
        super(x, y, SIZE, Color.BLUE);
        this.vertexID = ID;
    }
}


我想做的是使用List<Vertex> myVerticesObjectOutputStream写入文件,这要求每个类都实现Serializable接口。一个例子如下所示:

FileChooser fc = new FileChooser();
File fileChosen = fc.showOpenDialog(window);

try {
   FileOutputStream fOutStream = new FileOutputStream(fileChosen);
   ObjectOutputStream oOutStream = new ObjectOutputStream(fOutStream);

   oOutStream.writeObject(myVertices);
   oOutStream.close();
} catch {
    // Exception handling here
}


上面实现的问题在于,尽管Vertex实现了Serializable,但超类Circle及其超类Shape却没有实现Serializable。结果是该文件包含Vertex对象,但是所有Shape详细信息都丢失了,默认为0。

有没有解决此类问题的简单方法?我当前唯一的选择似乎是创建自己的Shape / Circle,将位置/显示数据存储为双精度,以便随后可以是Serializable。显然,对于一个类来说,这并不需要付出太多的努力,但是我还有其他一些Shape对象也想保存。我认为,然后必须构造实际的Shape对象以显示它们。

谢谢!

最佳答案

您需要创建一个writeObject / readObject方法来保存所需的其他状态。

Serialization - readObject writeObject overrides

Uses of readObject/writeObject in Serialization

Why are readObject and writeObject private, and why would I write transient variables explicitly?

Java Custom Serialization

Java: efficiency of writeObject vs writeExternal

09-30 17:49
查看更多