当类在Eclipse中实现Serializable时,我有两个选项:添加默认的serialVersionUID(1L)或生成的serialVersionUID(3567653491060394677L)。我认为第一个选项更酷,但很多次我看到人们使用第二个选项。是否有理由生成较长的serialVersionUID?
当前回答
Well, serialVersionUID is an exception to the rule that “static fields don’t get serialized”. ObjectOutputStream writes every time the value of serialVersionUID to the output stream. ObjectInputStream reads it back and if the value read from the stream does not agree with the serialVersionUID value in the current version of the class, then it throws the InvalidClassException. Moreover, if there is no serialVersionUID officially declared in the class to be serialized, compiler automatically adds it with a value generated based on the fields declared in the class.
其他回答
为了补充@David Schmitts的回答,作为经验法则,我总是使用默认的1L。我只需要返回并更改其中一些数几次,但当我进行更改并每次更新默认数时,我知道这一点。
在我目前的公司,他们要求自动生成的号码,所以我使用它作为约定,但我更喜欢默认的。我的观点是,如果这不是您工作的约定,请使用默认值,除非您认为由于某种原因将不断更改序列化类的结构。
如果您没有指定serialVersionUID,那么Java会动态生成一个。生成的serialVersionUID就是这个数字。如果您更改了类中的某些内容,而这些内容并没有真正使您的类与以前的序列化版本不兼容,而是更改了散列,那么您需要使用生成的非常大的数字serialVersionUID(或错误消息中的“预期”数字)。否则,如果你自己记录所有东西,0,1,2…是更好的。
Well, serialVersionUID is an exception to the rule that “static fields don’t get serialized”. ObjectOutputStream writes every time the value of serialVersionUID to the output stream. ObjectInputStream reads it back and if the value read from the stream does not agree with the serialVersionUID value in the current version of the class, then it throws the InvalidClassException. Moreover, if there is no serialVersionUID officially declared in the class to be serialized, compiler automatically adds it with a value generated based on the fields declared in the class.
据我所知,这只是为了与以前的版本兼容。只有当您之前忽略了使用serialVersionUID,然后进行了您知道应该是兼容的但导致序列化中断的更改时,这才有用。
有关更多细节,请参阅Java Serialization Spec。
每次定义时,绝对应该创建一个serialVersionUID 实现java.io.Serializable的类。如果你不这样做,别人会的 自动为你创建,但这很糟糕。自动生成 serialVersionUID基于类的方法签名,因此 如果您在将来更改类以添加方法(例如), 反序列化类的“旧”版本将失败。这就是 可能发生:
创建类的第一个版本,而不定义 serialVersionUID。 将类的实例序列化到持久存储中;一个 serialVersionUID为您自动生成。 修改类以添加新方法,并重新部署应用程序。 尝试反序列化在第2步中序列化的实例,但现在它失败了(当它应该成功时),因为它有 不同的自动生成serialVersionUID。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap