Serialization in java - Java @ Desk

Tuesday, July 23, 2013

Serialization in java

Serialization in java

What is serialization?
Serialization is a process to translate an object in a state/format that can be transferred over a network, stored in a file and the transmitted state/format can be used to get back the original object.
An object is converted to bytes and stored in a file. This process is called serialization.
Conversion of bytes into a original object is called de-serialization.

How to serialize an object in java?
Object need to implement the Serializable interface to make JVM understand that this object need to be serialize and may require opertaions like to store in a file or transferred over a network.
This interface is a marker interface and it does not have any methods.

Since the interface does not contain any method how will JVM understand to serialize this object?
To serialize an object, writeObject(object); method of java.io.ObjectOutputStream class is used.
To de-serialize an object, readObject() method of java.io.ObjectInputStream class is used.

writeObject(object) internally checks whether the object that needs to be serialized is an instance of Serializable interface or not. Here JVM applies a check on an object that needs to be serialized as shown below.
else if (obj instanceof Serializable) {
 writeOrdinaryObject(obj, desc, unshared);
}
SerialVersionUID
To make an object serialized, one must use serialVersionUID in the object. This field is used to check if the class that is getting de-serialized is compatible with which version of serialized object.
Once returned, the class serialVersionUID is compared to the serialVersionUID of the serialized class, and if there is a mismatch, the deserialization fails and InvalidClassException is thrown.
This is declared in a class as : private static final long serialVersionUID = 7526472295622776147L;

If field marked as transient or static then that field gets ignored by JVM and it does not gets serialized.
Since static members are associated with the class and they do not belong to the individual objects, they are not serialized. Static field values will be reinitialized to whatever value they are set to when the class is loaded.

For basic example of serialization in java, click here
Can static be serialized?, check here







No comments:

Post a Comment