简体   繁体   English

在Java的Serializable上,需要澄清

[英]On Java's Serializable, clarification needed

When implementing Serializable interface, in Java, we need to set it's serialVersionUID long. 在Java中实现Serializable接口时,我们需要将它的serialVersionUID设置为long。

Is there any differences whether default or auto generated long should be chosen? 是否应该选择默认值或自动生成的长度是否存在差异?

When should one be preferred over another? 什么时候应该优先于另一个?

If auto generated long is chosen, should it be changed in event class if changed? 如果选择了自动生成的long,是否应该在事件类中更改? In other words the value that gets assigned to serialVersionUID .. is it related to current structure of the class and fields and methods that are declared there? 换句话说,分配给serialVersionUID的值是它与类的当前结构以及在那里声明的字段和方法有关吗?

private static final long   serialVersionUID    = 1L;
private static final long   serialVersionUID    = 6749067740891125834L;

The main difference between the default and auto-generated long is that the auto-generated serial version UID is based on the fields of the object. 默认和自动生成的长度之间的主要区别在于自动生成的串行版本UID基于对象的字段。 If you have persisted copies of the object that don't have a version id, then using the generated version can help ensure compatibility with the objects that are already persisted. 如果您持有没有版本ID的对象的副本,则使用生成的版本可以帮助确保与已持久的对象的兼容性。 Because of this, I tend to use the generated versions. 因此,我倾向于使用生成的版本。 In either case, you need to update the version id if incompatible changes are made. 在任何一种情况下,如果进行了不兼容的更改,则需要更新版本ID。

http://docs.oracle.com/javase/1.5.0/docs/guide/serialization/spec/version.html section 5.6.1 and 5.6.2 describes what changes are compatible and what changes will break serialization. http://docs.oracle.com/javase/1.5.0/docs/guide/serialization/spec/version.html第5.6.1和5.6.2节描述了哪些更改是兼容的以及哪些更改会破坏序列化。

The serial version UID can be any number, its value has no specific meaning. 串行版本UID可以是任意数字,其值没有特定含义。

It makes sense and is convenient to start it with 1 and increment it every time the format changes. 它是有意义的,并且方便用1启动它并在每次格式改变时递增它。

You can only do that, however, if you thought about it from the beginning. 但是,如果你从一开始就考虑过它,那么你只能这样做。 If you already have existing data that you need to continue to be able to read, this data will have the auto-generated id. 如果您已经拥有需要继续读取的现有数据,则此数据将具有自动生成的ID。 In this case, you have no choice, but to match that value. 在这种情况下,您别无选择,只能匹配该值。

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

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