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.

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:"); = "Bhabani";
       this.age = 25;

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

   private void readObject(ObjectInputStream in) throws IOException,
           ClassNotFoundException {
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"); = "BHABANI PATTANAYAK";
       b.age = 33;
       ByteArrayOutputStream outStream = new ByteArrayOutputStream();
       ObjectOutputStream os = new ObjectOutputStream(outStream);
       ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
       ObjectInputStream in = new ObjectInputStream(inStream);
       Bean bean = (Bean)in.readObject();
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