What is a serial version UID used for?
我正在创建一个Java应用程序,并且当创建一个与ADT一起使用的接口时,它发现需要初始化一个随机数作为ID号。
1 2 3 4 5 6 7 | public class StackFullException extends RuntimeException { private static final long serialVersionUID = 1L; public StackFullException(){} public StackFullException(String message) { super(message); } } |
我很好奇,不提这件事是否会影响到我的计划,如果是这样,如何避免它。
EDCOX1(0)是Java序列化API的黑魔法的一部分。
它用于唯一标识类的版本,以便在对类进行反序列化时,可以对照
如果没有指定,序列化API将自己生成一个
通过自己添加字段,您可以控制这个过程—您可以决定何时对类的更改应中断旧版本的反序列化。
更多信息可以在Javadocs for
简而言之,如果您打算序列化这个类,然后稍后对它进行反序列化——但是在对代码进行了一些更改和重新编译等之后——这个字段或多或少是保证它按预期工作的必要条件。
The serialization runtime associates with each serializable class a
version number, called aserialVersionUID , which is used during
deserialization to verify that the sender and receiver of a serialized
object have loaded classes for that object that are compatible with
respect to serialization. If the receiver has loaded a class for the
object that has a differentserialVersionUID than that of the
corresponding sender's class, then deserialization will result in an
InvalidClassException . A serializable class can declare its own
serialVersionUID explicitly by declaring a field named
"serialVersionUID" that must bestatic ,final , and of typelong :
1 ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;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 unexpectedInvalidClassExceptions during
deserialization. Therefore, to guarantee a consistentserialVersionUID
value across different java compiler implementations, a serializable
class must declare an explicitserialVersionUID value.
此外,您可以在Java对象序列化规范中阅读更多有关此内容的内容。
此上下文中的uid还可用于区分写入磁盘的两个对象。
资料来源:http://www.mkyong.com/java-best-practices/understand-the-serialversionuid/
正如其他人所说,uid是可选的,不应该影响您的程序。
SearialVersionUid只是您在接口上放置的一个版本号,用来知道它正在与同一个API通信。换句话说,如果客户端的Java对象是"1L",服务器是"2L",那么它将抛出一个错误匹配错误。
它用于在与JDK的序列化一起使用时反映类的结构更改。完全可以选择使用。就我个人而言,我从来没有创建过这样的字段,当我找到它们时,我经常删除它们。