1L的Java SerialVersionUid可以吗?还是必须是独一无二的? [英] Is Java SerialVersionUid of 1L ok? Or does it need to be unique?

查看:74
本文介绍了1L的Java SerialVersionUid可以吗?还是必须是独一无二的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实现可序列化的 Java 类.我将它们都设置为 1L 的 serialVersionUid.

I have two java classes which implement Serializable. I set both of them to have a serialVersionUid of 1L.

一位同事说,所有的类都必须有一个唯一的串行版本 uid,如果它们具有相同的串行版本 uid,jvm 会将类视为平等.我认为相等是基于 equals 方法的结果,而不是基于串行版本的 uid.

A coworker said that all classes must have a unique serial version uid and that the jvm will treat classes as equal if they have the same serial version uid. I thought equality was based on the result of the equals method and not the serial version uid.

据我了解,串行版本 uid 用于指示类的版本,并且当类以不兼容的方式更改时,串行版本 uid 应该增加.

It was my understanding that the serial version uid was used to indicate the version of the class and that when the class changed in an incompatible fashion that the serial verison uid should be incremented.

这样对吗?可以使用 1 的串行版本 uid 吗?或者 Java 类应该永远不会有 1L 的串行版本 uid?

Is that correct? Is it okay to use a serialversion uid of 1? Or should java classes never have a serialversion uid of 1L?

推荐答案

类名是对象序列化表示的一部分.serialVersionUID 仅用于对类进行版本控制.所以 1L 是一个有效值.

The class name is part of the serialized representation of an object. The serialVersionUID is only used for versioning the classes. So 1L is a valid value.

注意,如果你不打算在进化类的同时保持序列化的兼容性,serialVersionUID是没有用的,你可以省略它.当您想要对类进行兼容更改并且仍然能够读取使用旧版本的类(或反之亦然)序列化的对象时,拥有 serialVersionUID 很有用.但这需要格外小心,而且绝非易事.您通常应该避免将序列化用于长期存储.如果用于网络目的,为客户端和服务器使用完全相同的类(即同时部署两者)是最简单的策略.

Note that if you don't plan to maintain the compatibility of serialization while evolving the class, serialVersionUID is useless, and you can just omit it. Having a serialVersionUID is useful when you want to make compatible changes to a class and still be able to read objects that were serialized using an older version of the class (or vice-versa). But that requires extreme care, and is far from being an easy task. You should generally avoid using serialization for long-term storage. If used for networking purpose, using the same exact classes for the client and the server (i.e. deploying both at once) is the easiest strategy.

另请注意,您可以通过简单地序列化和反序列化两个不同类的两个对象(具有与 serialVersionUID 相同的值 (1L))来轻松地证明您的同事他错了.如果他的理论是真的,JVM 将无法知道如何反序列化对象.

Also note that you could easily prove your coworker that he's wrong by simply serializing and deserializing two objects of two different classes having both the same value (1L) as serialVersionUID. If his theory was true, the JVM would have no way of knowing how to deserialize the objects.

这篇关于1L的Java SerialVersionUid可以吗?还是必须是独一无二的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆