从 Java 5 开始不再需要serialVersionUID?

发布于 2024-12-04 00:37:56 字数 108 浏览 0 评论 0原文

我最近读到一条评论,说从 Ja​​va 5 开始,不再需要使用serialVersionUID 来使同一类的不同版本兼容序列化/反序列化。这是正确的吗?也许它与协变返回类型混淆了。所以想和大家一起看看。

I recently read a comment saying that usage of serialVersionUID to make different versions of the same class compatible for serialization/deserialization is no longer needed from Java 5 onwards. Is this correct? Maybe it got mixed-up with covariant return types. So wanted to check it out with you all.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我只土不豪 2024-12-11 00:37:57

从 Java 1.4 开始,您就可以使用 XMLEncoder< /a> 用于序列化,这会忽略任何serialVersionUID,就像大多数其他序列化库一样。

但是,如果您使用ObjectOutputStream,其serialVersionUID的用法并没有改变。

Since Java 1.4 you have been able to use XMLEncoder for Serialisation and this ignores any serialVersionUID, as does most other serialisation libraries.

However if you use ObjectOutputStream, its usage of serialVersionUID has not changed.

嘿看小鸭子会跑 2024-12-11 00:37:56

JavaDocs for Java 5 仍然指出需要它:

如果可序列化类未显式声明serialVersionUID,则序列化运行时将根据该类的各个方面计算该类的默认serialVersionUID 值,如Java(TM) 对象序列化规范中所述。但是,强烈建议所有可序列化类显式声明serialVersionUID值,因为默认的serialVersionUID计算对类详细信息高度敏感,这些详细信息可能因编译器实现而异,因此可能会在反序列化期间导致意外的InvalidClassExceptions。因此,为了保证在不同的 java 编译器实现之间具有一致的serialVersionUID 值,可序列化类必须声明显式的serialVersionUID 值。还强烈建议显式的serialVersionUID声明尽可能使用private修饰符,因为此类声明仅适用于立即声明的类——serialVersionUID字段作为继承成员没有用处。

The JavaDocs for Java 5 still states that it is needed:

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文