【问题标题】:Serializing a serializable object passed over as Object序列化作为 Object 传递的可序列化对象
【发布时间】:2021-03-08 05:33:35
【问题描述】:

所以我有一个名为 Person 的类,它实现了 Serializable。

当我将 Person 的实例传递给名为“saveToFile(Object obj)”的方法时,我会这样做

class FileManager() implements IGateway{
    public void saveToFile(Object ms) throws IOException {
        OutputStream file = new FileOutputStream(PATH);
        OutputStream buffer = new BufferedOutputStream(file);
        ObjectOutput output = new ObjectOutputStream(buffer);

        // serialize
        output.writeObject((Person)ms); //cast to serializable class
        output.close();
    }
}
public class Person implements Serializable{
    private HashMap<String, HashMap<String, ArrayList<Message>>> messageBoxes;
    private IGateway iGateway;

    public Person(){
        iGateway = new MessageManager();
        messageBoxes = new HashMap<String, HashMap<String, ArrayList<Message>>>();
    }

    public void saveMessage(){
        iGateway.saveToFile(this);
    }
}
public interface IGateway {
    void saveToFile(Object obj) throws IOException;
}

这给了我 NotSerializableException。出于设计原因,我需要继续将 Person 实例作为 Object 接收。当我将它转换为可序列化类时,为什么它会一直给出 NotSerializableException?

【问题讨论】:

  • Person 类是什么样的?可以贴在这里吗?

标签: java object serialization casting serializable


【解决方案1】:

Person 类中的字段有自己的类型,不能是Serializable

例如这里:

  1. 您的HashMap 字段实现了默认的Serializable 接口,这没关系。
  2. 名为iGateway 的字段的类型为IGateway,默认情况下不可序列化

您必须使用可以处理此类事情的第三方库进行序列化,或者使其也可序列化。

您还可以使用自定义代码覆盖Person 类的writeObject,但请确保不要尝试序列化未实现此接口的其他对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2017-03-21
    相关资源
    最近更新 更多