Serialization in Java

Serialization is the process of converting an object's state into byte sequence (to persist it on to a file), and to rebuild (deserialize) those bytes into an object.

To make an object serializable, the object should implement java.io.Serializable interface. Lets take an example to understand Serialization in Java.

Firstly lets define a serializable object

###############################################################

package learn.java.serialization;

import java.io.Serializable;

public class SerializableObject implements Serializable{

private String message;
public SerializableObject(){
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}

###############################################################

As you must have noticed the only special thing that we have done  to the class is implement Serializable. The java.io.Serializable is a markup or marker interface, it allows the serialization mechanism to check object's ability to be persisted.

Now as we have defined a serializable object lets try to persist it onto a file 

###############################################################

package learn.java.serialization;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Serialize {
   public static void main(String[] args) {
      SerializableObject serializableObject = new SerializableObject();
  serializableObject.setMessage("This message will be serialized.");
  System.out.println("Trying to serialize object with message ### "+serializableObject.getMessage()+" ###");
  System.out.println(serializeObject(serializableObject));
  System.out.println("############################################");
  System.out.println("Trying to deserialize the serialized object");
   
      SerializableObject deserializableObject = deserializeObject();
  if(deserializableObject == null)
System.out.println("Some problem occured in de-serialization process.");
  else
System.out.println("Object de-serialized successfully with message ### "+deserializableObject.getMessage()+" ###");
   
   }
  private static String serializeObject(SerializableObject serializableObject){
  String msg = "";
  try {
  FileOutputStream fos = new FileOutputStream("C:/tmp/serializableTest.txt");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(serializableObject); // Initiates the Serialization process          
out.close();
msg = "Object serialized successfully, with message ### "+serializableObject.getMessage()+" ###";
  } catch (IOException e) {
e.printStackTrace();
msg = "Problem in serialization, problem ### "+e.getMessage()+" ###";
  }


  return msg;
  }
   
   private static SerializableObject deserializeObject(){
  SerializableObject serializableObject = null;

  try {
  FileInputStream fis = new FileInputStream(new File("C:/tmp/serializableTest.txt"));
ObjectInputStream in = new ObjectInputStream(fis);
// Initiates the (De)serialization  process
serializableObject = (SerializableObject) in.readObject(); 
  } catch (FileNotFoundException e) {
  e.printStackTrace();
  } catch (IOException e) {
e.printStackTrace();
  } catch (ClassNotFoundException e) {
  e.printStackTrace();
}
  return serializableObject;
  }
}
###############################################################

Here serializeObject method defines the logic of persisting an object to a file and deserializeObject method defines the logic of reading the serialized data from the file and recreates a new object into the memory.


Good to know about Serialization in Java

  • An object must implement the java.io.Serializable interface or inherit that implementation from its object hierarchy to make it persistable.
  • Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass along with the variables value. 
  • Mark a variable as transient to exclude it from serialization process
  • Since static variables belong to the class and not to an object they are not the part of the state of object so they are not saved during Java Serialization process.
  • A Serializable class must define all non-serializable variable as transient
  • It is recommended to define private static final serialVersionUID value which guarantees a consistent serialiVersionUID across different java implementations.
  • If a serializable class does not explicitly declare a serialVersionUID, then a default serialVersionUID value is calculated for that class based on various aspects of the class, as described in the Java Object Serialization Specification.
  • Serializable class can override following methods to specify custom serialization & deserialization process

   private void writeObject(ObjectOutputStream out) throws IOException
   private void readObject(ObjectInputStream in)  throws IOException,   ClassNotFoundException

  • Serialization process throws java.io.NotSerializableException  when you try to serialize a non serializable instance 
  • Implementing java.io.Externalizable is an alternative for java.io.Serializable, it allows the implementing class to define custom serialization process.

Comments

Popular posts from this blog

Custom PagingNavigator for SEO friendly URL

Importing / Indexing MySQL data into Solr

The Externalizable Interface