6 Jun


What is the SerialVersionUID?

When you declare a class as Serializable by implementing the marker interface java.io.Serializable, the Java runtime persists the instance of that class into the disk by using (a default) Serialization mechanism (default when no other customized mechanism is provided). During serialization, the Java runtime creates a version number for a class, so that it can de-serialize it later. This version number is known as SerialVersionUID in Java.

When declaring a class as Serilizable, the Eclipse IDE’s will give a warning against absence of SerialVersionUID e.g. “The Serializable class Customer does not declare a static final SerialVersionUID field of type long”.
If we don’t declare a SerialVersionUID. The serialVersionUID is a static, final and long value in our class. If it is not declared, the Serialization mechanism will create it for us. The compiler automatically adds it with a value generated based on the fields declared in the class.

Why it is needed?

The SerializationVersionUID is needed to check the versions between the serialized objects and the current class. Let’s say you are storing a serialized object of some class A. Now, the de-serialization of that object can occur after a period of time (e.g. a month) or on a completely different JVM (i.e. sending an object through the net using serialization). In both cases, the class definition of class A may have changed between the time of serialization and de-serialzation. The SerialVersionUID is there to have some kind of versioning system. It checks if the data read from the input stream is compatible with the current definition of the class.

Normally, static fields are not serialized but the serialVersionUID field is an exception to that rule. There is a nice example that can be found here. It shows what happens when first you serialize an object of a class with a serializationVersionUID set to 1 and then de-serialize that object using a different versionUID in the class. The example uses ObjectInputStream and ObjectOutputStream for reading from and writing to a file. If the value read from the stream does not agree with the serialVersionUID value in the current version of the class, then it throws the InvalidClassException.

Sometimes you don’t want to forbid de-serialization of old serialized objects as they are outdated. In other cases you want to keep them but “migrate” them to the new used version of the class. The serialVersionUID will help you to recognized if there is an old object you try to de-serialize.


Leave a Reply

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

− three = 2

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" extra="">