简体   繁体   English

类状态更改时的Java序列化和反序列化

[英]Java serialization and deserialization when the state of the class changes

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 当瞬变场变为非瞬变时

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: 在您的情况下:

  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 1 st case - your field would have a default value. 由于transient字段被序列化过程中忽略了,这种情况下几乎等于1日的情况下-你的领域将有一个默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM