gpt4 book ai didi

java - 如果父级没有无参数构造函数,则出现序列化问题

转载 作者:行者123 更新时间:2023-11-30 08:21:17 26 4
gpt4 key购买 nike

我正在尽力理解这个概念。但是我无法弄清楚这件事:

如果父类没有无参数构造函数,而且父类也没有实现 Serializable 接口(interface),如何序列化子类?

父类.java

public class Parent {
private String parentString;
public Parent(String parentString) {
this.parentString = parentString;
parentString = "Parent";
}
public String getParentString(){
return parentString;
}
}

子类.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)不是Serializable 并且没有无参数构造函数,则您不能直接序列化该对象。来自文档:

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.

(强调我的)

如果您可以修改父类,那么您应该简单地添加适当的无参数构造函数和/或让它适本地实现Serializable

如果您不能修改父类,那么您可能要考虑序列化一个代理类。您可以实现该方法

Object writeReplace() throws ObjectStreamException;

在你的 Child 中返回一个代理对象(它将被序列化而不是 Child 实例),并实现

Object readResolve() throws ObjectStreamException;

在代理类中返回等效的 Child 实例。

关于java - 如果父级没有无参数构造函数,则出现序列化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25341555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com