Thursday 19 April 2012

Customize the serialization process

According to me, there are 3 ways to  customize the serialization.
  1. Using transient keyword
  2. Defining readObject() and writeObject() method in the class to be serialized.
  3. Using the Externalizable interface.

1. Using transient keyword :

Let me demonstrate the use of transient keyword with the example. Look at the below code snippet.


import java.io.Serializable;
public class ThreadCls implements Serializable{

 private static final long serialVersionUID = -1730623665577892203L;
 private Thread thread;
 private Integer someData;
 
 public ThreadCls() {
  thread = new Thread();
  someData = 129;
 }
 
}

The java.land.Thread class is not implementing Serializable interface.Hence, the ThreadCls class throws an exception when this class is being serialized.
But indeed, the ThreadCls has to be serialized for us. We can achieve it by informing the JVM to not look at the instance variable "thread" during the serialization process. We can do that by designating the "transient" keyword to the "thread" instance variable.

import java.io.Serializable;
public class ThreadCls implements Serializable{

 private static final long serialVersionUID = -1730623665577892203L;
 private transient Thread thread;
 private Integer someData;
 
 public ThreadCls() {
  thread = new Thread();
  someData = 129;
 }
 
}

During the serialization of ThreadCls instance, the "transient" designated "thread" instance variable will not be serialized. During the de-serialization, the "transient" designated instance variable will be assigned with its default value.

2. Defining readObject() and writeObject() method : 

In a Serializable implemented class, if readObject and writeObject are defined, then the JVM would execute these methods for serialization and de-serialization of the objects respectively.
These methods can be defined with any access specifier, the JVM can execute these methods.In order to maintain the integrity of the class these methods can be defined as private. By this, the sub classes does not have the chance to override.

These methods can be used for seizing the serialization of the class which acquired the serialization property through its super classes.

3. Using the Externalizable interface : 

It is covered in the different blog post.

No comments:

Post a Comment