Java: When to add readObjectNoData() during serialization?

后端 未结 4 1672
广开言路
广开言路 2021-02-02 10:58

I am reading the serialization chapter in Effective Java. I am trying to understand the paragraph below, which is found in the book.

If you implemen

4条回答
  •  悲&欢浪女
    2021-02-02 11:25

    The readObjectNoData section in Java Object Serialization Specification seems interesting (see below).

    Your edits to the question give a perfect example. If Employee was serialized when it did not extend Person and later deserialized when it did then the Person part would be initialized to empty string and 0 age. Using this method, you can initialize them to "name" and 1 respectively.

    For serializable objects, the readObjectNoData method allows a class to control the initialization of its own fields in the event that a subclass instance is deserialized and the serialization stream does not list the class in question as a superclass of the deserialized object. This may occur in cases where the receiving party uses a different version of the deserialized instance's class than the sending party, and the receiver's version extends classes that are not extended by the sender's version. This may also occur if the serialization stream has been tampered; hence, readObjectNoData is useful for initializing deserialized objects properly despite a "hostile" or incomplete source stream.

    private void readObjectNoData() throws ObjectStreamException;

    Each serializable class may define its own readObjectNoData method. If a serializable class does not define a readObjectNoData method, then in the circumstances listed above the fields of the class will be initialized to their default values (as listed in section 4.5.5 of The JavaTM Language Specification, Second Edition); this behavior is consistent with that of ObjectInputStream prior to version 1.4 of the JavaTM 2 SDK, Standard Edition, when support for readObjectNoData methods was introduced. If a serializable class does define a readObjectNoData method and the aforementioned conditions arise, then readObjectNoData will be invoked at the point during deserialization when a class-defined readObject method would otherwise be called had the class in question been listed by the stream as a superclass of the instance being deserialized.

提交回复
热议问题