gpt4 book ai didi

java - 为什么 readObject 方法必须调用 defaultReadObject 以保持向后和向前兼容性

转载 作者:太空宇宙 更新时间:2023-11-04 13:18:00 26 4
gpt4 key购买 nike

我正在学习《Effective Java》,第 75 项:

If all instance fields are transient, it is technically permissible to dispense with invoking defaultWriteObject and defaultReadObject , but it is not recommended. Even if all instance fields are transient, invoking defaultWriteObject affects the serialized form, resulting in greatly enhanced flexibility. The resulting serialized form makes it possible to add nontransient instance fields in a later release while preserving backward and forward compatibility. If an instance is serialized in a later version and deserialized in an earlier version, the added fields will be ignored. Had the earlier version’s readObject method failed to invoke defaultReadObject , the deserialization would fail with a StreamCorruptedException

问题是为什么需要调用defaultReadObject/defaultWriteObject来保持向后和向前兼容性?

能举个例子解释一下吗?

为什么添加的字段会被忽略?

为什么会抛出StreamCorruptedException?

最佳答案

因为这就是默认情况下发生的情况。如果您添加这些方法,您至少必须执行如果它们不存在时会发生的情况。否则,您将无法以兼容的方式读/写流。您不能在不冒兼容性风险的情况下完全替换本来编写的内容。

除非你可以同时神奇地改变两端并且任何地方都没有永久序列化的流,例如在文件或数据库中。

关于java - 为什么 readObject 方法必须调用 defaultReadObject 以保持向后和向前兼容性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33363646/

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