java - 子类间序列化

标签 java serialization

在面试中被问到有一个 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/

相关文章:

python - 用于Docker集成的通用Python对象序列化

python - 如何使类 JSON 可序列化

java - 序列化有什么用?

java - 如何解析 Perforce JAVA API 中的集成文件

java - 我怎样才能驱逐 Spring Boot 中的所有缓存?

java - 在 Map 实现中搜索前缀的最佳方法是什么?

python - 如何序列化 pyspark 管道对象?

java - java是否有一个选项来控制启动进程时的CPU使用率

java - 如何使用 Jung 2 在图中用概率标记边

jquery - JSON ajax SyntaxError : JSON. 解析:意外字符