Wednesday, 13 February 2013

What is SerialVersionUID

SerialVersionUID is a unique identifier for each class , by which jvm compares the versions of class.If we don't provide this field explicitly , jvm generates it automatically for every class . The Algorithm for generating SerialVersionUID is highly dependent on the jvm version , and class structure . This id keeps on changing if the class structure is changed . When we Serialize a class , then change the class i.e. add or remove some fields(It will change the SerialVersionUID) , and then again de-serialize it ,we get the following exception :

java.lang.InvalidClassException 

because the SerialVersionUID of the class which we are trying to de serialize is different from the SerialVersionUID of current class , so JVM thrown an exception about these incompatible version . This is painful because classes are changed frequently and we have to face this exception every time . So we should add a SerialVersionUID ourselves , in that case JVM does not generate a SerialVersionUID , and it is fixed . So we do not get this exception again .

A warning is produced , if we implement Serializable but forget to include this field

The serializable class Serialzation does not declare a static final serialVersionUID field of type long

This field must be private static final long . 


if you are not using serialization in java or you don't intend to deserialize it again ,  you don't have to worry about it .