Serialization Version Control In Java


This article explains version control in serialization.
If you serialize an object, then you must have the same class to deserialize it and use the object. If you modify the class then that can cause incompatibility and that can cause deserialization to fail. There are some changes you can make to a class that do not prevent deserialization, but some do. 
Changes that affect deserialization
  1. Deleting an Instance Variable.
  2. Changing the type of an Instance Variable.
  3. Changing a non-transient variable to a transient variable.
  4. Moving a class up or down in the hierarchy.
  5. Changing an Instance Variable to static.
  6. Changing class from serializable to non-serializable.
Changes that do not affect deserialization
  1. Changing transient variables to non-transient variables
  2. Changing the access level of an Instance Variable
  3. Create a new Instance Variable in a class.

Importance of SerialVersion UID

Each time the object is serialized, it is stamped with a version id of the object's class. This is called a serial version UID. When the object is deserialized, if the class has changed since serialization, then the class could have a different version id and deserialization fails.
But it can be controlled by the user. If there is any possibility that the class may undergo some changes, then put the serial version UID in the class. 
When Java tries to deserialize an object, it compares the serialized object version UID with that of the class version UID that the JVM is using for deserialization. If two numbers do not match, then the JVM assumes that the class is not compatible for deserialization and it throws an exception. 
So, the solution is to put the version UID in the class. Since the class may undergo changes, the version UID will remain the same and deserialization can be done easily.

How to get the Version UID for the class?

Open a command prompt, got to the folder where your Java file is saved and type "serialver classname". 
Now paste this version UID into your class.
I hope this article was useful to you and thank you for reading it.

Similar Articles