Versioning and serialVersionUID

suggest change

When you implement java.io.Serializable interface to make a class serializable, the compiler looks for a static final field named serialVersionUID of type long. If the class doesn’t have this field declared explicitly then the compiler will create one such field and assign it with a value which comes out of a implementation dependent computation of serialVersionUID. This computation depends upon various aspects of the class and it follows the Object Serialization Specifications given by Sun. But, the value is not guaranteed to be the same across all compiler implementations.

This value is used for checking the compatibility of the classes with respect to serialization and this is done while de-serializing a saved object. The Serialization Runtime verifies that serialVersionUID read from the de-serialized data and the serialVersionUID declared in the class are exactly the same. If that is not the case, it throws an InvalidClassException.

It’s highly recommended that you explicitly declare and initialize the static, final field of type long and named ‘serialVersionUID’ in all your classes you want to make Serializable instead of relying on the default computation of the value for this field even if you are not gonna use versioning. ‘serialVersionUID’ computation is extremely sensitive and may vary from one compiler implementation to another and hence you may turn up getting the InvalidClassException even for the same class just because you used different compiler implementations on the sender and the receiver ends of the serialization process.

public class Example implements Serializable {          
    static final long serialVersionUID = 1L /*or some other value*/;
    //...
}

As long as serialVersionUID is the same, Java Serialization can handle different versions of a class. Compatible and incompatible changes are;

Compatible Changes

Incompatible Changes

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Serialization:
* Versioning and serialVersionUID

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
47 Serialization
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap