Why does the defaultWriteObject function have to be called first when writing into an ObjectOutputStream?

后端 未结 4 2082
清酒与你
清酒与你 2020-12-15 06:50

When I read the about the Serializable interface in Thinking in java, there is a sentence that says:

If you use the default

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 07:26

    Java Object Serialization Specification is vague on this subject:

    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.

    Here's an old thread which gives an example case when problems might occur.

    And here's a JBoss AS Jira ticket with another example.

提交回复
热议问题