Java serialization and deserialization when the state of the class changes

半世苍凉 提交于 2020-01-07 08:49:12

问题


How does serialization and deserialization work in the following cases:

  1. When a new field is added to the class.
  2. When a non static member is converted to static
  3. When a non transient field becomes transient
  4. When a transient field becomes non transient

回答1:


In all of the cases described above, the java.io.InvalidClassException would be thrown in case you try to deserialize the class. The reason of this behaviour is that a serial version of the class used for deserialization does not match a serial version of the class used for class serialization. That is default behaviour.

This serial version of the class is used to verify that the serialized and deserialized objects have the same attributes and thus are compatible (which is not the case in your examples in the question).

If you don't explicitly declare a serialVersionUID field (of type long), the JVM will generate one automatically at run-time. However, if you're going to use Java serialization it is highly recommended to declare a serialVersionUID explicitly (because the generated one is compiler-dependent and thus may result in unexpected exceptions of java.io.InvalidClassException).

Suppose you explicitly declared serialVersionUID but you don't updated it during the changes. In your cases:

  1. When a new field is added to the class. The object should de deserialized without any exceptions, a new field would have a default value.
  2. When a non static member is converted to static. Your static field would have a value of corresponding non-static field.
  3. When a non transient field becomes transient. Your transient field would be ignored during deserializtion and thus have a default value.
  4. When a transient field becomes non transient. Because transient fields are ignored during serialization, this case is almost equal to the 1st case - your field would have a default value.


来源:https://stackoverflow.com/questions/53354172/java-serialization-and-deserialization-when-the-state-of-the-class-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!