Java - Object Serialization Deserialization

What is Object Serialization?

Object Serialization is the process of converting an object in memory to a sequence of bytes and storing bytes in a file.

The process of reading the bytes produced by a serialization and restoring the object back in memory is called object deserialization.

The serialization of an object is also known as deflating or marshalling the object.

The deserialization of an object is also known as inflating or unmarshalling the object.

API

ObjectOutputStream class serializes an object.

ObjectInputStream class deserializes an object.

Your class must implement the Serializable or Externalizable interface to be serialized or deserialized.

The Serializable interface is a marker interface.

To make Person class serializable, declare the Person class as follows:

class Person implements Serializable {

}

Java takes care of the details of reading/writing a Serializable object from/to a stream.

Externalizable interface gives you more control in reading and writing objects from/to a stream.

It inherits the Serializable interface.

public interface Externalizable extends Serializable {
   void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;
   void writeExternal(ObjectOutput out) throws IOException;
}

Java calls the readExternal() method when reading an object from a stream.

It calls the writeExternal() method when writing an object to a stream.

Your class implementing the Externalizable interface looks like the following:

class Person implements Externalizable {
   public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
     // Write the logic to read the Person object fields from the stream
   }

   public void writeExternal(ObjectOutput out) throws IOException {
     // Write the logic to write Person object fields to the stream
   }
}

Related Topics