java中的serialVersionUID是什么,通常在异常类中?
可能的重复:
我为什么要担心serialVersionUID?
我正在执行一些异常处理代码并且我看到了名为serialVersionUID 的东西。这个uid是干什么用的??它只限于例外还是可以在所有类中使用???这个id有什么好处???
Possible Duplicate:
Why should I bother about serialVersionUID?
I am going through some exception handling code and i saw something named as serialVersionUID. What this uid is for?? Is it only limited to exception or can be used in all classes??? what is the advantage of this id???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
serialVersionUID
是一个字段,用于在序列化
时定义特定类的版本。反序列化
..考虑这样一个场景,您有一个类Employee
,它有3个字段,并且已经在生产中使用了一段时间(意味着可能存在许多员工对象的序列化版本) ,当您更新要包含的类(例如第四个字段)时,所有先前的类(已序列化的)都无法转换或反序列化为新的类。你会得到一个例外。为了避免此问题,您可以使用
serialVersionUID
字段告诉JVM
新类实际上是不同的版本(通过更改serialVersionUID
>)。@Farmor
&@Tom Jefferys
说了几乎同样的事情,但是通过一个例子,事情看起来要简单得多。serialVersionUID
is a field to define the version of a particular class whileseriializing
&deseriializing
.. consider a scenario where you have a classEmployee
which has 3 fields which has been in production for some time (meaning there may exist many serialized versions of employee objects), when you update the class to include (say a 4th field) then all the previous class (which are serialized) cannot be casted or de-serialized to the new one & you'll get an exception.to avoid this issue, you can use the
serialVersionUID
field to tellJVM
that the new class is in fact of a different version (by changing theserialVersionUID
).@Farmor
&@Tom Jefferys
said pretty much the same thing, but with an example things look a lot simpler.它用于序列化,应该在任何实现
Serialized
的类中声明。它实际上是 JVM 可以用来检查序列化类是否与您尝试将其反序列化到的类定义相匹配的版本号。
这里有更多信息:http://下载.oracle.com/javase/1,5.0/docs/api/java/io/Serializable.html
It's used for serialization, it should be declared in any class that implements
Serializable
.It's effectively a version number the JVM can use to check if a serialized class matches the class definition you're trying to deserialize it into.
There's more information on it here: http://download.oracle.com/javase/1,5.0/docs/api/java/io/Serializable.html
确定它们是否具有可序列化和反序列化兼容性,如果它们具有相同的
serialVersionUID
并且都实现了Serialized
那么它们是兼容的。而且它不仅限于异常,因为您会注意到,如果 Eclipse 实现了
Serializable
,它很容易在普通 java 类的早期放置一个serialVersionUID
。编辑:更新为包括 @Spychos 关于
Serialized
接口的正确注释。It's to determine if they have serializable and deserializable compatibility if they have the same
serialVersionUID
and both implementsSerializable
then they are compatible.And it's not limited to exceptions only as you will notice eclipse is prone to put a
serialVersionUID
early in your normal java class if it implementsSerializable
.Edited: Updated to include @Spychos correct comment about the
Serializable
interface.