Thursday, January 3, 2013

Serialization in Java

Serialization is used to save the object and all of its instance variables (except transient) in an external file mostly with .ser extension. With the help of Serialization you can reconstruct the same object latter.

The Serialization is done with the help of below two methods

// serialize objects and write them to a stream

// read the stream and deserialize objects

About the example - We have a Dog class, which we will be Serializing. Note that Class which to be serialize must implements the Serializable interface. Serializable is a marker interface, it has no methods to implement. In we will create a Dog object d1 serialize it and write it to a dog.ser file and latter we will deserialize the object.

Please see the java codes below

Points to be remembered about Serialization

1. If the instance variables are itself references to objects then we just have to take care of the class whose instance to be saved rest will be taken care by serialization automatically.
For example - If Dog object has Collar reference and you serialize a Dog object, the Collar will be serialized automatically. And if the Collar class contained a reference to another object that object would also be serialized and so on. And the only object you have to worry about saving and restoring is the Dog.

2. Reference class must also implements Serializable otherwise you would get Exception - If you don't have access to source code of reference class then you can mark the object as transient, it says skip the particular object during serialization.
For example - If you mark the Dog's Collar instance variable with transient, then serialization will simply skip the Collar during serialization.

3. Serialization Is Not for Statics. Static variables are never saved as part of the object's state because they do not belong to the object.

No comments:

Post a Comment