在面试中被问到有一个 A
类没有实现 serializable
接口(interface),如下所示
class A
{
private int a;
A( int a)
{
this.a = a;
}
}
还有一个类 B
扩展了 A
并且还实现了 serializable
接口(interface)
class B extends A implements serializable
{
private int a , b;
B(int a, int b)
{
this.a = a;
this.b = b;
}
}
现在请告诉我是否可以序列化类 B
,前提是类 A
没有序列化假设我想序列化类 B
,能不能搞定。
最佳答案
如果不修改 A 使其具有可访问的无参数构造函数,则无法序列化 B。
来自 java.io.Serializable 的 javadoc
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.
During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable.
关于java - 子类间序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15761987/