The serialization runtime is associated with each serializable class using a version number called Serialversionuid, which is used during deserialization to verify that the sender and receiver of the serialized object have loaded a serialization-compatible class for the object.
If the serialversionuid of the object's class that the recipient loads differs from the version number of the corresponding sender's class, the deserialization will result InvalidClassException
.
A serializable class can "serialVersionUID"
long
explicitly declare its own serialversionuid by declaring a field that is named (the field must be static (static), eventually (final)):
Any-access-modifier static final Long Serialversionuid = 42L
If the serializable class does not explicitly declare Serialversionuid, the serialization runtime calculates the default Serialversionuid value for the class based on the 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 the SERIALVERSIONUID value because the calculation of the default Serialversionuid has a high sensitivity to the details of the class and may vary widely depending on the compiler implementation. This can result in an unexpected process during deserialization InvalidClassException
. Therefore, to ensure consistency of serialversionuid values across different Java compilers, the serialization class must declare an explicit SERIALVERSIONUID value. It is also strongly recommended that private
you use modifiers to display the declaration Serialversionuid, if possible, because this declaration applies only to the direct declaration class-The Serialversionuid field is not useful as an inherited member. An array class cannot declare an explicit serialversionuid, so they always have a default computed value, but the array class does not have a requirement to match the Serialversionuid value.
The role of the Serialversionuid field in the Serializable interface