Serialization – Compatible and Incompatible modifications to classes

April 15, 2010

Hello,
Java Serialization allows us to write an Object into byte stream and again re-construct its state whenever needed.
In between Serialization and De-serialization the class definition might get changed. Some modifications in
the class definition would result in java.io.InvalidClassException while De-serializing.
It is very important to understand these constraints. especially while dealing with Enterprise distributed Applications. As Distributed applications would always exchange the objects over the network stream using Serialization techniques.

Modifications those keep the Class compatible with Serialized version

  1. Add Fields
  2. Change Field from Static to Non-Static.
  3. Change Field from Transient to Non-Transient
  4. Add Class to the Object Tree


Modifications those make the Class incompatible with Serialized version

  1. Delete Field
  2. Change Field from Non-Static to Static
  3. Change Field from Non-Transient to Transient
  4. Changing the Class hierarchy
  5. Changing type of a Primitive Field

There are others changes as well those can be added to above list. They can be found here.
If you look at the above list the gist is “Addition of Field is permitted while Deletion cause Exception“.
Changing Field from Static to Non-static for transient to non-transient is kind of adding field to existing class.
While making non-static field to static and data-type of the field is like deleting the field which is incompatible.

This seems quite obvious from the Java Documentation but a beginner level would find this helpful, which is the reason
behind this post.

Cheers !

Amit