当类在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.

其他回答

因为在许多情况下,默认id不是唯一的。所以我们创建id是为了创造独特的概念。

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.io.Serializable的类。如果你不这样做,别人会的 自动为你创建,但这很糟糕。自动生成 serialVersionUID基于类的方法签名,因此 如果您在将来更改类以添加方法(例如), 反序列化类的“旧”版本将失败。这就是 可能发生:

创建类的第一个版本,而不定义 serialVersionUID。 将类的实例序列化到持久存储中;一个 serialVersionUID为您自动生成。 修改类以添加新方法,并重新部署应用程序。 尝试反序列化在第2步中序列化的实例,但现在它失败了(当它应该成功时),因为它有 不同的自动生成serialVersionUID。

为了补充@David Schmitts的回答,作为经验法则,我总是使用默认的1L。我只需要返回并更改其中一些数几次,但当我进行更改并每次更新默认数时,我知道这一点。

在我目前的公司,他们要求自动生成的号码,所以我使用它作为约定,但我更喜欢默认的。我的观点是,如果这不是您工作的约定,请使用默认值,除非您认为由于某种原因将不断更改序列化类的结构。

据我所知,这只是为了与以前的版本兼容。只有当您之前忽略了使用serialVersionUID,然后进行了您知道应该是兼容的但导致序列化中断的更改时,这才有用。

有关更多细节,请参阅Java Serialization Spec。