本文介绍了如果父类不实现可序列化,则序列化子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Employee2 extends Employee1 {}

public class Employee1  extends Employee0 {}

public class Employee0  {}

现在我序列化 Employee2 类和

Now i serialize the Employee2 class and

get the error  java.io.NotSerializableException: Employee2

现在如果将 Employee1 类 def 更改为

Now if changed Employee1 class def to

public class Employee1  extends Employee0 implements java.io.Serializable {}

它工作正常,但请注意 Employee0 仍然没有实现 Serializable

it works fine but please note Employee0 still does not implement Serializable

Base 类是否必须实现 Serializable 才能序列化子类?如果是,为什么它只对 Employee1 强制,而对 Employee0 不强制?

Is it mandatory for Base class has to implement Serializable to serialize the child class? If yes why its mandatory only for Employee1 but not for Employee0 ?

根据我的示例,它看起来是这样,但根据网络上的其他文章,这不应该是强制性的.那么我在这里缺少什么?

As per my example it looks like yes but as per other articles on net this should not be mandatory. So what i am missing here?

推荐答案

如果你想序列化一个 Employee2 对象,Employee2 必须实现 Serializable(最好是直接而不是继承它).你没有得到异常是因为 Employee1 不可序列化,你得到它是因为 Employee2 不是,你无论如何都试图序列化它.

If you want to serialize an Employee2 object, Employee2 has to implement Serializable (preferably directly rather than inheriting it). You weren't getting the exception because Employee1 isn't serializable, you were getting it because Employee2 isn't, and you tried to serialize it anyway.

Employee1Employee0 不一定要实现 Serializable,但如果没有,它们就必须没有参数构造函数(以便序列化程序可以实例化重构的 Employee2 对象).

Employee1 and Employee0 don't necessarily have to implement Serializable, but if they don't, they have to have no-argument constructors (so that the serializer can instantiate the reconstructed Employee2 object).

这篇关于如果父类不实现可序列化,则序列化子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 19:57