gpt4 book ai didi

java - 子类的序列化

转载 作者:行者123 更新时间:2023-12-02 03:22:51 25 4
gpt4 key购买 nike

我刚刚读了Serialization文档,对此感到有点惊讶(强调我的):

The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The default mechanism for saving the Object's fields can be invoked by calling out.defaultWriteObject. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.

因此,在以下情况下不能保证父类(super class)会被序列化:

public class MySuperClass implements Serializable{
public int a;
}

public class MySubClass extends MySuperClass{
public int b;
}

MySubClass msc = new MySubClass();
msc.a = 10
msc.b = 20

//serialize msc

那么,反序列化的 msc.a 的值是 10 还是 0 是特定于实现的?

最佳答案

在您摘录的段落上方的文档中,它表示在序列化和反序列化过程中需要特殊处理的类必须实现特殊方法。这些方法是 @Beethoven 提到的 writeObject 和 readObject 方法。

至于您提出的有关 msc.a 值的问题,它肯定是 10。如果您的父类(super class)没有实现可序列化,但子类实现了,则该值将为 0。即使您的父类(super class)没有实现可序列化,您也可以在 noarg 构造函数中为 msc.a 指定默认值。

关于java - 子类的序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39395007/

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