为什么不自动生成serialVersionUID? [英] Why isn't the serialVersionUID automatically generated?

查看:550
本文介绍了为什么不自动生成serialVersionUID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不自动生成 serialVersionUID ?我在应用程序服务器上遇到了一个问题,显然是在缓存旧类。

Why isn't the serialVersionUID automatically generated? I was running into an issue on an application server where apparently an old class was being cached.

推荐答案

serialversionuid不会自动生成,因为有危险。当设置serialversionuid时,它意味着类的两个版本在序列化方面是兼容的。

serialversionuid is not automatically generated because it is dangerous. When serialversionuid is set, it implies that two versions of a class are compatible with respect to serialization.

想象一下你有一个名为Foo的类,它有 no serialversionuid (默认值),并将Foo实例序列化为文件。稍后,您将向Foo类添加一些新成员。如果您尝试从文件反序列化Foo对象,您将收到序列化失败,指出对象不兼容。他们 不兼容,这是你想要的并且是默认的。它们是不兼容的,因为Foo类中的新成员无法从旧的序列化Foo实例初始化。

Imagine you have a class called Foo, and it has no serialversionuid (the default), and you serialize an instance of Foo to a file. Later, you add some new members to the Foo class. If you try to deserialize the Foo object from the file, you will get a serialization failure stating that the objects are incompatible. They are incompatible, this is what you want and is the default. They are incompatible because new members in the Foo class cannot be initialized from the old serialized instance of Foo.

现在,你可能会说,我不在乎,在我的应用程序可以接受这些字段未初始化。如果确实是,则可以将 new Foo类的serialversionuid设置为与 Foo类相同。这将告诉Java这些对象与serializablity兼容,当你将旧的Foo实例反序列化为新的Foo类时,Java不会抱怨(但是新的字段仍然是未初始化的)。

Now, you might say, "I don't care, in my application it is acceptable for those fields to be uninitialized". If that really is the case, you can set the serialversionuid of the new Foo class to be the same as the old Foo class. This will tell Java that the objects are compatible with respect to serializablity, and Java will not complain when you deserialize the old Foo instance into the new Foo class (but the new fields will still be uninitialized).

如果您是第一次创建新课程,并且设置了serialversionuid,则 您正在输入合同 。该合同是,对于具有相同serialversionuid的此类的所有未来版本,我将保证它们在状态和序列化方面兼容

If you are creating a new class for the first time, and you set the serialversionuid, you are entering a contract. That contract is, "For all future versions of this class with the same serialversionuid, I will guarantee they are compatible with respect to state and serialization".

如果您更改了某个类,并且显式希望禁止旧版本的反序列化,则可以将serialversionuid更改为新值。如果尝试将旧对象反序列化为新的类实例,这将导致抛出异常。

If you change a class, and you explicitly want to disallow deserialization of old versions, you can change the serialversionuid to a new value. This will cause an exception to be thrown if an old object is attempted to be deserialized into a new class instance.

这篇关于为什么不自动生成serialVersionUID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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