Thursday 19 April 2012

What is serialVersionUID?

In order to understand the use of serialVersionUID, you must have an understanding of serialization in java. You can find the article about it at serialization in java.

serialVersionUID is used for version control in the serialization.

In the serialization process, if the class does not have the serialVersionUID JVM generates one by considering the instance variable and other factors of the class. If any filed in the class is modified or deleted or added then the serialVersionUID generated by the JVM is different from the one that generated earlier.

For instance, an object is persisted on flat file for long duration. During that time, the has been modified by adding a new instance variable. If we try to deserialize the object from the file system it throws java.io.InvalidClassException because the serialVersionUID of the object in the file system is different from the one in the JVM for that class. As a developer, we expect the JVM to assign a default value for the newly added variable and deserialize the remaining object.

This can be achieved by explicitly defining the serialVersionUID in the class. We must ensure to not change the this variable value once it is defined. By this we can avoid serialization process to throw java.io.InvalidClassException even though the class definition is changed.

static final long serialVersionUID = 10275539472837495L;

Simple way to generate it is by using the Eclipse IDE. Once your class implements the Serializable interface, Eclipse start giving the warnings to generate the SerialVersionUID. You can click on the warnings and chose the compiler generated to generate the SerialVersionUID.







Or you can use the utility comes along with the JDK called serialver.

No comments:

Post a Comment