【发布时间】: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