问题
How does serialization and deserialization work in the following cases:
- When a new field is added to the class.
- When a non static member is converted to static
- When a non transient field becomes transient
- 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:
- 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.
- When a non static member is converted to static. Your static field would have a value of corresponding non-static field.
- When a non transient field becomes transient. Your transient field would be ignored during deserializtion and thus have a default value.
- When a transient field becomes non transient. Because
transient
fields are ignored during serialization, this case is almost equal to the1
st case - your field would have a default value.
来源:https://stackoverflow.com/questions/53354172/java-serialization-and-deserialization-when-the-state-of-the-class-changes