首页 > 学院 > 开发设计 > 正文

Java序列化中的serialVersionUID有什么用?

2019-11-15 00:26:57
字体:
来源:转载
供稿:网友
java序列化中的serialVersionUID有什么用?

如果一个实现了Serializable的类没有serialVersionUID属性,IDE(比如Eclipse)通常会报这样一个warning:

The serializable class Foo does not declare a static finalserialVersionUID field of type long

那这个serialVersionUID是做什么用的呢?可以看看JDK中Serializable接口的注释。

The serialization runtime associates with each serializable class aversion number, called a serialVersionUID, which is used duringdeserialization to verify that the sender and receiver of aserialized object have loaded classes for that object that arecompatible with respect to serialization. If the receiver has loadeda class for the object that has a different serialVersionUID thanthat of the corresponding sender's class, then deserialization willresult in an InvalidClassException}. A serializable class candeclare its own serialVersionUID explicitly by declaring a fieldnamed "serialVersionUID" that must be static, final, andof type long:

serialVersionUID 表示可序列化类的版本,在反序列化对象时,用来确认序列化与反序列化该对象所使用的类的版本是否兼容。如果类的版本不一致,那么反序列化将不能正常进行,抛出InvalidClassException。

If a serializable class does not explicitly declare aserialVersionUID, then the serialization runtime will calculate adefault serialVersionUID value for that class based on variousaspects of the class, as described in the Java(TM) ObjectSerialization Specification. However, it is stronglyrecommended that all serializable classes explicitly declareserialVersionUID values, since the default serialVersionUIDcomputation is highly sensitive to class details that may varydepending on compiler implementations, and can thus result inunexpected InvalidClassExceptions duringdeserialization. Therefore, to guarantee a consistentserialVersionUID value across different java compilerimplementations, a serializable class must declare an explicitserialVersionUID value. It is also strongly advised that explicitserialVersionUID declarations use the PRivate modifierwhere possible, since such declarations apply only to the immediatelydeclaring class--serialVersionUID fields are not useful as inheritedmembers. Array classes cannot declare an explicit serialVersionUID,so they always have the default computed value, but the requirementfor matching serialVersionUID values is waived for array classes.

如果一个可序列化的类没有包含serialVersionUID,运行时会根据这个类的特征自动计算出一个serialVersionUID。那么,为什么不能用默认的这个实现呢,似乎更省事?因为不同的编译器实现会导致同一个类的源代码文件,被计算出不同的serialVersionUID.

StackOverflow上有一个类似的问题:http://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it点击下面这个链接,可以查看更多关于Serializable接口的信息:https://github.com/ZhaoX/jdk-1.7-annotated/blob/master/src/java/io/Serializable.java


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表