简体   繁体   English

java标准对象的serialVersionUID可以改变吗?

[英]Can serialVersionUID of java standard objects change ?

On a project, we have several objects serialized. 在一个项目中,我们有几个序列化的对象。 It will be necessary to use these objects on machine with different JVM (possibly different versions). 有必要在具有不同JVM(可能是不同版本)的机器上使用这些对象。

Our objects serialVersionUID are fixed and won't change, but we are concerned about the serialVersionUID of the JVM standard objects, for instance ArrayList/HashSet that are used in our serialized objects. 我们的对象serialVersionUID是固定的,不会改变,但是我们关注JVM标准对象的serialVersionUID,例如我们的序列化对象中使用的ArrayList / HashSet。

So the question is, can these serialVersionUID change between different versions of JVM or between different JVM ? 所以问题是,这些serialVersionUID可以在不同版本的JVM之间或不同JVM之间进行更改吗?

Or do we have to use another serialization mechanism to support different JVMs ? 或者我们是否必须使用另一种序列化机制来支持不同的JVM?

The serialVersionUID should only be changed if there is a change to the class that would not be compatible with previously serialized versions of it. 只有当类的更改与以前的序列化版本不兼容时,才应更改serialVersionUID。

To see what changes would potentially break compatibility check the Specification 要查看哪些更改可能会破坏兼容性,请检查规范

I highly doubt that a new version of Java would introduce any changes to core classes that would break compatibility. 我非常怀疑新版本的Java会对核心类引入任何会破坏兼容性的更改。

We use serialVersionUID as a version code for the class, and we should change this field when we modify the class. 我们使用serialVersionUID作为类的版本代码,我们应该在修改类时更改此字段。 This field is used as identity of the class in deserialization. 该字段在反序列化中用作类的标识。

For example, you serialize a object of class A and save it in an binary file, you can deserialize file to the original object later. 例如,序列化类A的对象并将其保存在二进制文件中,稍后可以将文件反序列化为原始对象。 But if you add a field to A and do not change the serialVersionUID, the deserialization may return a malformed object. 但是,如果向A添加字段并且不更改serialVersionUID,则反序列化可能会返回格式错误的对象。 And if you change the serialVersionUID , the deserialization will reject the input and throw an exception. 如果更改serialVersionUID ,反序列化将拒绝输入并抛出异常。 An exception is better than a unknown error. 异常优于未知错误。

These error/exception happen if and only if you used an old serialization result to create a instance of a modified class. 当且仅当您使用旧的序列化结果来创建已修改类的实例时,才会发生这些错误/异常。 If you don't use serialization for data persistence, there won't be any problems. 如果不使用序列化进行数据持久化,则不会出现任何问题。

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

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