我正在尽力理解这个概念。但我无法弄清楚这件事:
如果父类没有无参数构造函数,并且父类没有实现 Serialized 接口(interface),如何序列化子类?
Parent.java
public class Parent {
private String parentString;
public Parent(String parentString) {
this.parentString = parentString;
parentString = "Parent";
}
public String getParentString(){
return parentString;
}
}
Child.java
public class Child extends Parent implements Serializable{
private String childString;
public Child(String childString) {
super(childString);
this.childString = childString;
}
public String getChildString(){
return childString;
}
}
测试序列化.java
public class TestSerialization {
public static void main(String[] args) throws IOException, ClassNotFoundException{
Child child = new Child("Child");
FileOutputStream fos = new FileOutputStream(new File("file.ser"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(child);
oos.close();
FileInputStream fis = new FileInputStream(new File("file.ser"));
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj = ois.readObject();
ois.close();
Child castChild = (Child) obj;
System.out.println(castChild.getParentString());
System.out.println(castChild.getChildString());
}
}
它在读取对象时给了我一个异常,说 java.io.InvalidClassException: test.Child;没有有效的构造函数。如何序列化此类对象?
最佳答案
如果对象的父类(super class)之一不是可序列化
并且没有无参数构造函数,则无法直接序列化该对象。来自文档:
To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.
(强调我的)
如果您可以修改父类,那么您应该简单地添加适当的无参数构造函数和/或让它根据需要实现Serialized
。
如果您无法修改父类,那么您可能需要考虑序列化代理类。您可以实现该方法
Object writeReplace() throws ObjectStreamException;
在您的 Child
中返回一个代理对象(它将被序列化而不是 Child
实例),并实现
Object readResolve() throws ObjectStreamException;
在代理类中返回等效的 Child
实例。
关于java - 如果父级没有无参数构造函数,则出现序列化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25341555/