Overview of Serialization
Serialization is the process of writing complete state of java object into output stream, that stream can be file or byte array or stream associated with TCP/IP socket.
Deserialization is the process of reading back that serialized java object stream from input stream.
A java object is serializeable and deserializeable if that class follows the following rules
A) The java class must implement java.io.Serializable interface or java.io.Externalizable interface or inherit that implementation from any one of it’s super class implementation.
B) All instance variables of that class must implement Serializable interface or Externalizable interface or inherit from one of it’s super class.
All primitive data types and some of standard java API classes are serializable. You need not explicitly implement Serializable or Externalizable interfaces for those classes. Serialization process ignores class (static) variables.
Externalizable interface allow to do your own custom implementation of serialization. In this section, focus is only on Serializable interface.
We will talk initially about Serializable interface. This is a marker interface and does not have any methods. All major java technologies like RMI, EJB are based on serialization process to pass the objects through network. These technologies implicitly do all the serialization work for you. You need to simply implement the java.io.Serialzable interface, but If you want to do your own serialization, that is reading from or writing to streams, ObjectInputStream and ObjectOutputStream can be used.
These methods help to write into stream and read from stream
ObjectInputStream.readObject(); // to read object
ObjectInputStream.writeObject(Object obj); // to write object
Initially, We need to understand the default mechanism of serialization process in order to improve performance.
The default mechanism:
When you write or read an object to a file or network or other stream using serialization process, It writes/reads the complete object state that means it writes the object, it’s instance variables, and super class instance variables except transient variables and class (static) variables. Look at this object hierarchy.
In this class hierarchy, when I write CorporateEmployee object into file and and read from that file, Initially Address is called, second HomeAddress is called, third Employee is called and finally CorporateEmployee is called. So Total object hierarchy will be written into file except transient and class (static) variables. Initially super class will be called and so on till end of heirarchy. You need to keep an eye on this mechanism and act up on that, otherwise you will end up with writing everything.
