Customize java serialization.

We can customize java serialization by providing the readObject() and writeObject() methods in the serializable class.
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.


Example:
Serializable class:
public class Bean implements Serializable {
   private static final long serialVersionUID = 8381419946118107894L;
   public String name;
   public int age;


   public Bean() {
       System.out.println("constructor:");
       this.name = "Bhabani";
       this.age = 25;
   }


   private void writeObject(ObjectOutputStream out) throws IOException {
       this.name = "bbc";//This value will be stored in serialization
       out.defaultWriteObject();
   }


   private void readObject(ObjectInputStream in) throws IOException,
           ClassNotFoundException {
       in.defaultReadObject();
   }}
The Main class:
public class Test {
   public static void main(String[] args)throws Exception {
       
       Bean b = new Bean();
       System.out.println("Jst before read object");
       b.name = "BHABANI PATTANAYAK";
       b.age = 33;
       ByteArrayOutputStream outStream = new ByteArrayOutputStream();
       ObjectOutputStream os = new ObjectOutputStream(outStream);
       os.writeObject(b);
       os.flush();
       os.close();
       ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
       ObjectInputStream in = new ObjectInputStream(inStream);
       Bean bean = (Bean)in.readObject();
       System.out.println("Name:"+bean.name+"\nAge:"+bean.age);
   }
}
Here the bean object contains name as “BHABANI PATTANAYAK”  But the writeObject() method sets the name as “bbc” . So while serializing it takes the name as “bbc”.

No comments:

Post a Comment