serialVerionUID in Java Object Serialization
What is serialVersionUID?The purpose of the "serialVersionUID" is to keep track of different versions of a class in order to perform valid deserialization of objects. This SUID should be unique to a certain version of a class, and should be changed when there are any details change to the class, such as a new field, which would affect the structure of the serialized object.
The serialization process associates a serialVersionUID (default if not explicitly defined) with each serialized instance of a class. This serialVersionUID is validated at the time of deserialization from the loaded class serialVersionUID, and in case of a mismatch InvalidClassException is thrown.
If a serializable class does not define serialVersionUID explicitly then the serialization process automatically calculates a default serialVersionUID (by invoking computeDefaultSUID() method of java.io.ObjectStreamClass) value for that class viz usually the hash value of class details.
- Since default generation is dependent on the class details, it will change as soon as any detail of the class changes (for eg. added a new field in class).
- Even if you do not make any changes to class details there is a possibility of having different serialVersionUID if generated using different JVM implementations. That's why it is always recommended to define serialVersionUID manually in a Serializable class.
"serialVersionUID"that must be static, final, and of type
long in the Serializable Class defination
ANY-ACCESS-MODIFIER static final long serialVersionUID = 1L;
NOTE: serialVersionUID is case-sensitive
By defining serialiVersionUID in your Serializable class you can make sure that for different implementation of JVMs' serialVersionUID will be the same.
When should the serialVersionUID be changed?
Changes for which the guarantee of interoperability (serialization-deserialization) cannot be maintained, serialVersionUID of that class should be changed.
For details Types of changes affecting Serialization process click here
Using serialVer utility to generate serialVersionUID
You can use serialver utility provided by JDK to generate serialVersionUID of a class. It is present in the bin directory of your JDK.
On running following on command prompt
will generates following output
learn.java.serialization.SerializableObject: static final long serialVersionUID = 2873835861766732915L;