gpt4 book ai didi

java - 为什么在写入 ObjectOutputStream 时必须首先调用 defaultWriteObject 函数?

转载 作者:搜寻专家 更新时间:2023-10-30 19:45:50 25 4
gpt4 key购买 nike

当我读到Thinking in java中关于Serializable接口(interface)的时候,有一句话是这样说的:

If you use the default mechanism to write the non-transient parts of your object, you must call defaultWriteObject( ) as the first operation in writeObject( ), and defaultReadObject( ) as the first operation in readObject( ).

并且在 docs.oracle.com 5.6.2 :

Adding writeObject/readObject methods - If the version reading the stream has these methods then readObject is expected, as usual, to read the required data written to the stream by the default serialization. It should call defaultReadObject first before reading any optional data. The writeObject method is expected as usual to call defaultWriteObject to write the required data and then may write optional data.

所以如果我不先调用defaultWriteObject,如果我在那个调用之前写了别的东西,会有什么问题吗?我已经尝试过了,但在我的示例中它似乎仍然运行良好。那么如果有任何问题,它会在什么条件下发生?

最佳答案

Java 对象序列化规范在这个主题上含糊不清:

Either ObjectOutputStream's defaultWriteObject or writeFields method must be called once (and only once) before writing any optional data that will be needed by the corresponding readObject method to restore the state of the object; even if no optional data is written, defaultWriteObject or writeFields must still be invoked once. If defaultWriteObject or writeFields is not invoked once prior to the writing of optional data (if any), then the behavior of instance deserialization is undefined in cases where the ObjectInputStream cannot resolve the class which defined the writeObject method in question.

这是一个 old thread这给出了可能出现问题的示例。

这是一个 JBoss AS Jira ticket再举一个例子。

关于java - 为什么在写入 ObjectOutputStream 时必须首先调用 defaultWriteObject 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16239239/

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