serialVersionUId in Serialization

serialVersionUID is the only static field that gets serialized during object serialization.It basically represents the version of the class.

package com.serialize.example;import java.io.Serializable;

public class SerializationExample implements Serializable{

private static final long serialVersionUID = 1L;
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

 

If we don’t declare it then the compiler throws the following warning:The serializable class SerializationExample does not declare a static final serialVersionUID field of type long.

If we don’t declare it, then during object serialization, a serialVersionUID is generated at run time and is also serialized.The dynamically generated serialVersionUID is a 64-bit hash of the class name, interface class names, methods and fields. For example:-6317291996449964275L.

What is the use of serialVersionUId?

When an object is serialized, the serialVersionUID is serialized along with the other contents.Later when the object is deserialized, the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class.If the numbers do not match then, InvalidClassException is thrown.If the loaded class is not having a serialVersionUID declared, then it is automatically generated at runtime.

It is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value.

The serialVersionUID represents your class version, and you should increment it if the current version of your class is not backwards compatible with its previous version.

package com.serialize.example;import java.io.Serializable;

public class SerializationExample implements Serializable{

private static final long serialVersionUID = 1L;
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

Now, when we rename the attribute name to name1, we increment the serialVersionUId to 2L

package com.serialize.example;

import java.io.Serializable;

public class SerializationExample implements Serializable{

private static final long serialVersionUID = 2L;
private String name1;

public String getName1() {
return name1;
}

public void setName1(String name1) {
this.name1 = name1;
}

}

Leave a Reply

Your email address will not be published. Required fields are marked *