Monday, 25 April 2016

How to use different Serialization methods ?


When you implement Serializable, JVM does the serialization automatically using classes : 
ObjectInputStream and ObjectOutputStream

If we want to change the default serialization , there are 4 methods you can override :
1. readObject(ObjectInputStream ois)
If overridden, it is used to read the object from stream.

2. writeObject(ObjectOutputStream oos)
If overridden, it is used to write the object to stream.

3. Object writeReplace()
If overridden, after serialization it serializes the returned object to the stream.


4.Object readResolve()
If overridden, after deserialization it returns the final object to the caller program.
Also used to implement Singleton pattern with Serialization.

* All these methods are private so that subclasses can’t override them and used for Serialization only.


public class Pojo implements Serializable, ObjectInputValidation {
    private String msg;

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

    public String getMsg() {
        return 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();
    }
    private Object readResolve() throws ObjectStreamException {
        System.out.println("readResolve");
        return this;
    }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.