Java 规范统计
The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException.
enter code here
但是如果我如下分配所有类相同的序列版本 id
static final long serialVersionUID = 1L;
现在我所有的类都将具有相同的 serialversionUID,这将永远不会导致 InvalidclassException。
我知道我们明确地给出了它,因此它的值在不同的 JVM 实现中保持不变。
请让我知道为所有类放置相同的 id 有什么用,如果我们在序列化和反序列化之间修改类会发生什么?
最佳答案
我相信 serialVersionUID
仅用于确定已序列化的那个类的版本 - 类名也始终存在,因此它不会导致任何歧义。
Please let me know what is the use of putting same id for all the classes
它们实际上是不相关的值。使用 1 并在每次进行重大更改时递增它很简单。
what will happen if we modify class in between serialization and deserialization ?
这完全取决于您所做的修改类型。如果您只是添加或删除方法或静态字段,那很好 - 无论如何都不会影响序列化数据。如果您对实例字段进行任何更改,那是生活变得多毛的时候。您需要详细研究序列化格式以确切地计算出什么会构成重大更改,但完全有可能仅更改字段名称就可能破坏一切 - 例如如果字段按名称顺序序列化。
您可能需要考虑使用二进制数据格式,这种格式在数据格式更改时播放得更愉快,例如 Protocol Buffers . (还有其他好处,例如便携性和速度 - 而且 protobuf 也不是唯一的游戏。)
关于java - 所有类的序列号都相同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26045065/