【问题标题】:NotSerializableException after adding to ArrayList添加到 ArrayList 后的 NotSerializableException
【发布时间】:2015-07-26 08:37:41
【问题描述】:

所以我有一个名为 World 的类:

public class World implements Serializable {

    private int dx;
    private int dy;
    private int x;
    private int y;
    private Path path;
    public ImageIcon image;
    public ArrayList<Location> locations;

在将对象添加到 ArrayList&lt;Location&gt; locations; 之前,我正在对其进行序列化和反序列化处理。

现在当我尝试运行序列化时

try {
    FileOutputStream fos = new FileOutputStream(Main.board.worldpath.toString());
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(Main.board.world.image);
    oos.writeObject(Main.board.world);
    oos.close();
}catch (FileNotFoundException ex) {
    ex.printStackTrace();
} catch (IOException ex) {
    ex.printStackTrace();
}

它在oos.writeObject(Main.board.world);这一行抛出java.io.NotSerializableException: sun.nio.fs.WindowsPath

Location 类也是可序列化的:

public class Location implements Serializable {
    public int x;
    public int y;
    public String name;
    public String desc;

我不知道为什么它会说它不可序列化,那么序列化 ArrayLists 有什么特别之处吗?

【问题讨论】:

    标签: java serialization arraylist


    【解决方案1】:

    问题在于“路径”。该类不可序列化。 例如,您可以将“路径”保存为字符串并在加载时创建新路径。

    为其实现 readObject 和 writeObject 并使路径瞬态。

    【讨论】:

    • 谢谢,我把它改成了字符串,现在可以使用了。奇怪的是,我一直在用那里的路径加载和保存这些世界,但它从来没有给我抛出异常。
    • 可能一直到现在都是null
    猜你喜欢
    • 2020-11-08
    • 2013-01-03
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多