2023-java-study / book-study

북 스터디 기록 레포지토리
0 stars 0 forks source link

[Item 86] 직렬화 가능 상위 클래스를 추가하는 경우 #195

Open ssstopeun opened 10 months ago

ssstopeun commented 10 months ago

p. 458에 보면

기존의 직렬화 가능 클래스에 직렬화가능 상위 클래스를 추가하는 드문 경우를 위한 메서드다.

라고 되어있는데 이해가 안됩니다! 어떤식으로 추가하게 되는지 어떤상황에서 쓸 수 있을지 궁금합니다.

NuhGnod commented 10 months ago

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 The Java Language Specification); this behavior is consistent with that of ObjectInputStream prior to version 1.4 of the Java 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.

제가 이해한 상황으로는, 어떤 클래스의 인스턴스가 직렬화 된 이후에, 해당 클래스가 변경(필드가 변경되거나, 책에서 말한 상황?)되었다면, 역직렬화시 문제가 생길 겁니다. 그래서 이러한 경우 해당 필드들을 기본값으로 세팅하는 readObjectNodata 메소드가 사용되는 것이 아닌가 하고 이해했습니다!