Serialization


Serialization

It is the process of converting the Java code Object into a Byte Stream, to transfer the Object Code from one Java Virtual machine to another and recreating it using the process of Deserialization. Java Serialization is used in Hibernate, RMI, JPA, EJB, and JMS technologies.
The serialization and deserialization process is platform-independent, which means we can serialize an object in a platform and deserialize the same object on a different platform.

Need for serialization:

  • Deep Copy
  • Caching
  • Communication
  • Persistence
  • Cross JVM Synchronization

To make a java object serializable, we must implement the java.io.Serializable interface. Serializable is a marker interface that has no data member and the method might get a certain capability.

For serializing an object,Use writeObject() method of class ObjectOutputStream.

Syntax:

public final void writeObject(Object o) throws ClassNotFoundException
For deserialization an object,
Use readObject() method of class ObjectInputStream.

Syntax:

public final Object readObject() throws ClassNotFoundException

Advantages:

  • It is easy and simple to understand
  • It is universally accepted by the developers
  • It supports encryption, compression, and authentication
  • Does not require third party software for execution

Disadvantages:

  • When Serializing, the opacity of an abstract data type can be broken.
  • Serializing all data members using Trivial Implementation may violate encapsulation.

Points to remember:

    1. If a parent class has implemented a Serializable interface then the child class does not need to implement it.

    2. Only non-static data members are used for the Serialization process.

    3. Static data members and transient data members are not used for the Serialization process.

    4. Associated objects must implement a Serializable interface.

Example:

Com.knowledge2life public class Employee implements java.io.Serializable { public String name=”Knowledge2life”; public String address=”India”; public transient int SSN; public int number; public void mailCheck() { System.out.println("Mailing a check to " + name + " " + address); } }

OUTPUT:

Mailing a check to Knowledge2life India