[英]Java serialization and deserialization when the state of the class changes
How does serialization and deserialization work in the following cases: 在以下情况下,序列化和反序列化如何工作:
In all of the cases described above, the java.io.InvalidClassException
would be thrown in case you try to deserialize the class. 在上述所有情况下,如果您尝试反序列化该类,将抛出java.io.InvalidClassException
。 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. 如果未显式声明serialVersionUID字段( long
类型),则JVM将在运行时自动生成一个。 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
). 但是,如果要使用Java序列化,强烈建议显式声明一个serialVersionUID (因为生成的序列依赖于编译器,因此可能导致java.io.InvalidClassException
意外异常)。
Suppose you explicitly declared serialVersionUID but you don't updated it during the changes. 假设您显式声明了serialVersionUID,但是在更改期间未进行更新。 In your cases: 在您的情况下:
transient
fields are ignored during serialization, this case is almost equal to the 1
st case - your field would have a default value. 由于transient
字段被序列化过程中忽略了,这种情况下几乎等于1
日的情况下-你的领域将有一个默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.