Customize Default Serialization Protocol

18/12/2011

Do you know how to customize the default behaviour of the serialization protocol? Tom Cruise starrer MI4 hits theatres this week in India and we experience unusual media frenzy. In no way this is realted but by impulse I mention about MI4 here. In this article I am going to write on how to customize Ghost protocol, oops serialization protocol.

One of my reader was asked a quesion in an interview on how to customize the serialization behaviour and this article serves as an answer for that question.

In general there are three approaches to serialization in java:

  1. Implement Serializable and use default protocol.
  2. Implement Serializable and get a chance to modify the default protocol.
  3. Implement Externalizable and write your own protocol to implement serailization.

Here protocol means, the way (process or approach) object is serialized and de-serialized.

We have seen enough about using the default protocol to implement serialization and how instances are created during serialization. In this current article we shall see about modifying the default protocol.

import java.io.Serializable;

public class Lion implements Serializable {
  private String sound;
  public Lion() {
    System.out.println("Lion's constructor invoked.");
    setSound("roar");
  }
  public String getSound(){
    return sound;
  }
  public void setSound(String sound){
    this.sound = sound;
  }
}

Above is a simple java class which we are going to use to demonstrate serialization. First let use do simple straight forward serialization and then make the customization in step 2.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class JavaSerialize {

  public static void main(String args[]) throws IOException, ClassNotFoundException {
    Lion leo = new Lion();
    // serialize
    System.out.println("Serialization done.");
    FileOutputStream fos = new FileOutputStream("serial.out");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(leo);

    // deserialize
    FileInputStream fis = new FileInputStream("serial.out");
    ObjectInputStream ois = new ObjectInputStream(fis);
    Lion deserializedObj = (Lion) ois.readObject();
    System.out.println("DeSerialization done. Lion: " + deserializedObj.getSound());
  }
}

Output:

Lion's constructor invoked.
Serialization done.
DeSerialization done. Lion: roar

Above class just uses the standard mechanism and demonstrates serialization using Lion class.

Customize Java Serialization

We know Serializable is a java marker interface. When a class implements Serializable interface it gives information to the JVM that the instances of these classes can be serialized. Along with that, there is a special note to the JVM

look for following two methods in the class that implements Serializable. If found invoke that and continue with serialization process else directly follow the standard serialization protocol.

So this gives us a chance to write these two methods insided the Class that implements Serializable and you get a hook to the serialization process. You can write your custom code inside these two methods and customize the standard behaviour of serialization.

  • private void writeObject(ObjectOutputStream out) throws IOException;
  • private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

I have modified the Lion class to include these two methods and on the fly I change a property of Lion to demonstrate this. This is not overriding or overloading methods and this is a mechanism provided by serialization. These two included methods are declared private but JVM can access the private methods of an object. There is no change to the class that does the serialization and de-serialization.

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Lion implements Serializable {
  private String sound;
  public Lion() {
    System.out.println("Lion's constructor invoked.");
    setSound("roar");
  }
  public String getSound(){
    return sound;
  }
  public void setSound(String sound){
    this.sound = sound;
  }

  private void writeObject(ObjectOutputStream out) throws IOException {
    setSound("meow");
    out.defaultWriteObject();
  }

  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
  }
}

Output:

Lion's constructor invoked.
Serialization done.
DeSerialization done. Lion: meow
Ads by Google

21 comments on “Customize Default Serialization Protocol

  1. SIr…!!!thank you so much for sharing this article..!
    it clears my concept about serialization.
    thank you.

  2. In order to control de-serialization of a Singleton object, which is serializable, we can add a method readResolve():

    // This method is called immediately after an object of this class is deserialized.
    // This method returns the singleton instance.
    protected Object readResolve() {
    return singleton;
    }

    While de-serializing, JVM calls this method, so you can always return the same object always inspite of the Serializable object being Singleton.

  3. As usual, awesome article. Now that you are so much getting into serialization, can we expect one more article explaining the use of “serialVersionUID” in serialization?

    Just a small request. See if that can be fulfilled.

    And keep the good work as usual. ;-)

  4. hi,

    i am bit confused with de-serialization. can u explain wat really happens while de-serializing the object and how constructor’s behave.

  5. Good Article on Serialization and Deserialization .

  6. Thanks for this article, could you please explain about Externalizable in you own way for my better understanding.
    Thanks in Advance.

  7. Ads by Google
  8. Sir,
    can I write normal static class
    If Not why
    and i am able to write a inner static class why it is allowed ?

  9. thank you so much for the detailed explanation.

  10. great article bro.i love ur articles a lot bcz they are very simple and very clear.plz keep posting ur articles bro.
    Thank you

  11. Sir can you give and example in your way about externalizable interface

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

ABOUT
I am Joe, author of this blog. I run javapapers with loads of passion. If you are into java, you may find lot of interesting things around.
Ads by Google
STAY in TOUCH:

Email:

Core Java | Servlet | JSP | Design Patterns | Android | Spring | Web Service | © 2008-2012 javapapers.