What is a serial version UID used for?
This question already has an answer here:
The serialVersionUID
is part of the black magic of the Java serialization API.
It is used to uniquely identify a version of the class so that when a class is de-serialized the version can be checked against the version of the class loaded by the ClassLoader
.
The serialization API will generate a serialVersionUID
itself if none is specified but this is then subject to random change by inconsequential changes (or at least ones that don't break serialization compatibility).
Adding the field yourself gives you control over this process - you decide when a change to the class should break de-serialization of older versions.
More information can be found in the JavaDocs for Serializable
.
In short, if you plan to serialize this class and then de-serialize it later - but after making some changes to code and recompiling etc - this field is more-or-less essential to guarantee that this will work as intended.
The Serializable
interface gives enough detail in this regard:
The serialization runtime associates with each serializable class a version number, called a serialVersionUID
, 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 different serialVersionUID
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 be static
, final
, and of type long
:
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 unexpected InvalidClassExceptions
during deserialization. Therefore, to guarantee a consistent serialVersionUID
value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID
value.
Also you can read more about this in Java Object Serialization Specification
searialVersionUID is just a version number you place on the interface to know it's communicating with the same API. In other words, if the client's Java Object is "1L" and the server's is "2L" then it will throw a missmatch error.
链接地址: http://www.djcxy.com/p/23836.html上一篇: Java可序列化:serialVersionUID的重要性?
下一篇: 什么是串行版本UID用于?