Java 序列化作为对象传递的可序列化对象
所以我有一个名为Person的类,它实现了Serializable 当我将Person的实例传递给名为“saveToFile(Object obj)”的方法时,我会这样做Java 序列化作为对象传递的可序列化对象,java,object,serialization,casting,serializable,Java,Object,Serialization,Casting,Serializable,所以我有一个名为Person的类,它实现了Serializable 当我将Person的实例传递给名为“saveToFile(Object obj)”的方法时,我会这样做 class FileManager() implements IGateway{ public void saveToFile(Object ms) throws IOException { OutputStream file = new FileOutputStream(PATH);
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();
}
}
这给了我NotSerializableException。出于设计原因,我需要继续接收Person实例作为对象。当我将NotSerializableException强制转换为serializable类时,为什么它会一直给出NotSerializableException?Person类中的字段有自己的类型,这些类型不能
serializable
例如:
HashMap
字段实现了一个默认的Serializable
接口,这是正常的iGateway
的字段的类型为iGateway
,默认情况下,不可序列化您还可以使用自定义代码覆盖
Person
类的writeObject
,但请确保不要尝试序列化未实现此接口的其他对象。Person类的外观是什么?你能把它贴在这里吗?
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;
}