Tuesday, 6 October 2015

Serialization Methods: readObject(), writeObject(), writeReplace(),readResolve()

Java serialization is automatic by implementing Serializable interface. The implementation is present in the ObjectInputStream and ObjectOutputStream classes.

But what if we want to change the default Serialization (we have some sensitive information in the object and before saving/retrieving we want to encrypt/decrypt it.

There are four methods that we can provide in the class to change the serialization behavior.

1.readObject(ObjectInputStream ois): If this method is present in the class, ObjectInputStream readObject() method will use this method for reading the object from stream.

2.writeObject(ObjectOutputStream oos): If this method is present in the class, ObjectOutputStream writeObject() method will use this method for writing the object to stream.

3.Object writeReplace(): If this method is present, then after serialization process this method is called and the object returned is serialized to the stream.

4.Object readResolve(): If this method is present, then after deserialization process, this method is called to return the final object to the caller program. This method is used to implement Singleton pattern with Serialized classes.

All four methods are kept as private so that subclasses can’t override them. They are meant for serialization purpose only and keeping them private avoids any security issue.


import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputValidation;
import java.io.ObjectStreamException;
import java.io.Serializable;

public class Pojo implements Serializable, ObjectInputValidation {

       public Pojo(String msg) {
              this.msg = msg;
       }
       private String msg;

       private void writeObject(java.io.ObjectOutputStream out)
                     throws IOException {
              System.out.println("writeObject");
              out.defaultWriteObject();
       }

       private Object writeReplace() throws ObjectStreamException {
              System.out.println("writeReplace");
              return this;
       }

       private void readObject(java.io.ObjectInputStream in)
                     throws IOException, ClassNotFoundException {
              System.out.println("readObject");
              in.registerValidation(this, 0);
              in.defaultReadObject();
       }

       @Override
       public void validateObject() throws InvalidObjectException {
              System.out.println("validateObject");
       }

       private Object readResolve() throws ObjectStreamException {
              System.out.println("readResolve");
              return this;
       }

       public String getMsg() {
              return msg;
       }
}



No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...