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:



Table Of Contents