Monday, July 19, 2010

Object Serialization And De-Serialization In Java

Implementing serialization in Java is pretty straight forward just a little step task. The class you want to be serialized just have to implements a marker Interface Serializable no override nothing extra work.

The JVM will take care of serialization and deserialization process automatically. Now you can write your object to any persistent technology e.g. database, file system or even over the network.

Serialization: The process of writing bits and bytes of a java object to physical stream.

Deserialization: The process of reading bits and bytes from physical stream to construct a java object.

Implementing serialization straight forward or lightly may cause problems in future. Let’s discuss some issues that can be faces.

If you not implement serialVersionUID, when you are saving the object JVM automatically calculate serialVersionUID depending upon the various class factors. So when deserialization reading object back it again calculate the serialVersionUID of the persistent object and to whom class it going to referenced. If class structure changed after saving object then a ClassCastException will be thrown.

JVM takes significant time to generate serialVersionUID at runtime, so having serialVersionUID generated will also improve the performance.

So always be sure to have serialVersionUID, follow the guidelines to implement serialVersionUID.

  • Always include it as field, “private static final long serialVersionUID = 1L”, include this field even in the first version of the class, as a reminder of its important.
  • Do not alter the value of this field in future versions, unless you are knowingly making changes to the class which will result in incompatible with all old serialized objects.
  • In Windows, generate serialVersionUID using JDK’s graphical tool like so: issue the like following
    serialver –show persistentClassName/Path
  • Most of modern IDEs can generate serialVersionUID, like in My Eclipse if you are implement Serializable interface, it will show a bulb sign clicking on it will indicate to generate serialVersionUID automatically by the IDE.

No comments:

Post a Comment