Java Serialization - BEHIND JAVA

Java Serialization

Share This

In java serialization what it actually do is write the java object into a stream so that it can be transported through a network and that object rebuilt again. For serialize an object you should implement the marker interface 'Serializable' to the currosponding object class (Serializable is a marker interface, so you dont need to override any method on the implementing class). It just inform the java class that this class can be serialized. Also you can tag properties that should not serialized as 'transient' (static variables are also not serialized).

What is SerialVersionUID?

SerialVersionUID is an ID which is stamped on object when it get serialized. Generally hashcode is used as SerivalVersionUID if you are not explicitly specify the SerialVersionUID. It is actually used for the version control of serialized object. If you not specify the SerialVersionUID explicitly then when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch.

Tools to findout serialVersionUID of an Object?

Java provides some tools for finding SerialVersionUID of an object, which is 'Serial Version Inspector'. For getting that go to java bin folder then type serialver -show. It result a swing application for finding SerialVersionUID.

How to customize the serialization process?

Classes ObjectInputStream and ObjectOutputStream- are high-level streams that contain the methods for serializing and deserializing an object.

The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out:

public final void writeObject(Object x) throws IOException

The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object:

public final Object readObject() throws IOException, 
                                 ClassNotFoundException

This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type.If you define these two methods in your class then JVM will invoke these two methods instead of applying default serialization mechanism.

You can customize behavior of object serialization and deserialization here by doing any kind of pre or post processing task. Important point to note is making these methods private to avoid being inherited, overridden or overloaded. Since only Java Virtual Machine can call private method integrity of your class will remain and Java Serialization will work as normal.

No comments:

Post a Comment

Pages