Java serialization and deserialization gives you the power to efficiently store and retrieve the object states whenever needed.

Why I need this serialization?

Now let me tell you the most simple example imagine you are playing some game on your phon

and somebody knocks your door. You simply pause the game and after opening the doors you get back to your game by pressing the RESUME button.


In other words you simply saved your current state of the game when you clicked the button “PAUSE”.


What happens you click RESUME button?

You just deserialize the previously serialized object and you get back to saved level of the game.


What is serialization?

This is the super power given by java to store instance means current state of the object so that it can be used further when needed.


What is deserialization?

Deserialization is simply the process to get back your saved instance.


How can I achieve this using java?

To serialize the instance we must implement the Serializable interface.


So example is class Student needs to be serialized so here is the code.


Step1: the class should implement serializable interface


package com.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;

import
java.io.Serializable;

class Student implements Serializable

{

       private String studentName;

       private int   rollNo;

       public String
getStudentName() {

              return studentName;

       }

       public void
setStudentName(String
studentName) {

              this.studentName = studentName;

       }

       public int getRollNo() {

              return rollNo;

       }

       public void setRollNo(int rollNo) {

              this.rollNo = rollNo;

       }


}

}


Step2:

You must have file where you will write the serialized object.


File file=new File(“emp.txt”);


Step3: You must have FileOuptputStream to stream data to the file.


FileOutputStream fos=new FileOutputStream(file);


Step4: Now create the object of ObjectOuputStream to put data on the 

FileOuptputStream


 

ObjectOutputStream objOut=new ObjectOutputStream(fos);


Step5:Create the Object that needs to be serialized.

Student studObj=new Student();

studObj.setStudentName(“Shiv”);

studObj.setRollNo(1);


Step6: Pass the created object to the 

ObjectOutputStream.


try {

objOut.writeObject(studObj);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


Please go through the whole program again.


private static void serializeMyObject()
{

              ObjectOutputStream
objOut=null;

              File
file=new File(“emp.txt”);

              FileOutputStream
fos;

              try {

                     fos=new FileOutputStream(file);

                    

                     objOut=new ObjectOutputStream(fos);

              }
catch
(FileNotFoundException
e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();

              }
catch (IOException e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();

              }

              Student
studObj=new Student();

              studObj.setStudentName(“Shiv”);

              studObj.setRollNo(1);

             

              try {

                     objOut.writeObject(studObj);

              }
catch (IOException e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();

              }

             

       }




Deserialization of Object.




In the previous section you saw how we serialized the object and saved it in the file.

So In this section we need to get back the data from our previously serialized object this is how we achieve this.

Step 1: The class should implement Serializable interface.


Please refer previously created Student class


Step 2: You must have file to read the serialized object.


File f=new File(“emp.txt”);


Step 3: You must have FileInputStream to stream data from the file.


FileInputStream 
fis=
new FileInputStream(file);


Step 4: Now create the object of ObjectInputStream to put data on the 

FileInputStream.

 

ObjectInputStream objectInputStream = new
ObjectInputStream(fis);


Step5: Get the

deserialized object.


Student
studObj=null;

try {

                     studObj=(Student)objectInputStream.readObject();

              }
catch
(ClassNotFoundException
e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();

              }
catch (IOException e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();
              }



Please go through the whole program again.


private static void
deserializeMyObject() {

              ObjectInputStream
objectInputStream = null;

              Student
studObj=null;

              try {

                     objectInputStream = new ObjectInputStream(new FileInputStream(new File(“emp.txt”)));

              }
catch (FileNotFoundException
e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();

              }
catch (IOException e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();

              }

              try {

                     studObj=(Student)objectInputStream.readObject();

              }
catch
(ClassNotFoundException
e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();

              }
catch (IOException e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();

              }

             

              System.out.println(“Deserialized
Objects Values”
);

              System.out.println(“RollNo :
+studObj.getRollNo());

              System.out.println(“Name : “+studObj.getStudentName());

       }



Complete Program on Serialization and Deserialization


package com.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;

import
java.io.Serializable;

class Student implements Serializable

{

       private String studentName;

       private int   rollNo;

       public String
getStudentName() {

              return studentName;

       }

       public void
setStudentName(String
studentName) {

              this.studentName = studentName;

       }

       public int getRollNo() {

              return rollNo;

       }

       public void setRollNo(int rollNo) {

              this.rollNo = rollNo;

       }

}

public class SerializationDemo {

       public static void main(String[] args) {

              serializeMyObject();

              deserializeMyObject();

       }

       private static void
deserializeMyObject() {

              ObjectInputStream
objectInputStream = null;

              Student
studObj=null;

              try {

                     objectInputStream = new ObjectInputStream(new FileInputStream(new File(“emp.txt”)));

              }
catch
(FileNotFoundException
e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();

              }
catch (IOException e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();

              }

              try {

                     studObj=(Student)objectInputStream.readObject();

              }
catch
(ClassNotFoundException
e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();

              }
catch (IOException e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();

              }

             

              System.out.println(“Deserialized
Objects Values”
);

              System.out.println(“RollNo :
+studObj.getRollNo());

              System.out.println(“Name : “+studObj.getStudentName());

       }

       private static void serializeMyObject()
{

              ObjectOutputStream
objOut=null;

              File
file=new File(“emp.txt”);

              FileOutputStream
fos;

              try {

                     fos=new FileOutputStream(file);

                    

                     objOut=new ObjectOutputStream(fos);

              }
catch
(FileNotFoundException
e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();

              }
catch (IOException e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();

              }

              Student
studObj=new Student();

              studObj.setStudentName(“Shiv”);

              studObj.setRollNo(1);

             

              try {

                     objOut.writeObject(studObj);

              }
catch (IOException e) {

                     // TODO Auto-generated
catch block

                     e.printStackTrace();

              }

             

       }

}


Now what if i don’t want some data to be seralized?

use transient keyword before that variable 


package com.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;

import java.io.Serializable;

class Student1 implements Serializable

{

       transient
private String studentName;

       private
int   rollNo;

       public
String getStudentName() {

              return
studentName;

       }

       public
void setStudentName(String studentName) {

              this.studentName
= studentName;

       }

       public
int getRollNo() {

              return
rollNo;

       }

       public
void setRollNo(int rollNo) {

              this.rollNo
= rollNo;

       }

}

public class checkTransient {

       public
static void main(String[] args) {

              serializeMyObject();

              deserializeMyObject();

       }

       private
static void deserializeMyObject() {

              ObjectInputStream
objectInputStream = null;

              Student1
studObj=null;

              try
{

                     objectInputStream
= new ObjectInputStream(new FileInputStream(new File(“emp.txt”)));

              }
catch (FileNotFoundException e) {

                     //
TODO Auto-generated catch block

                     e.printStackTrace();

              }
catch (IOException e) {

                     //
TODO Auto-generated catch block

                     e.printStackTrace();

              }

              try
{

                     studObj=(Student1)objectInputStream.readObject();

              }
catch (ClassNotFoundException e) {

                     //
TODO Auto-generated catch block

                     e.printStackTrace();

              }
catch (IOException e) {

                     //
TODO Auto-generated catch block

                     e.printStackTrace();

              }

              try
{

                     objectInputStream.close();

              }
catch (IOException e) {

                     //
TODO Auto-generated catch block

                     e.printStackTrace();

              }

              System.out.println(“Deserialized
Objects Values”);

              System.out.println(“RollNo
: “+studObj.getRollNo());

              System.out.println(“Name
: “+studObj.getStudentName());

       }

       private
static void serializeMyObject() {

              ObjectOutputStream
objOut=null;

              try
{

                     objOut=new
ObjectOutputStream(new FileOutputStream(new File(“emp.txt”)));

              }
catch (FileNotFoundException e) {

                     //
TODO Auto-generated catch block

                     e.printStackTrace();

              }
catch (IOException e) {

                     //
TODO Auto-generated catch block

                     e.printStackTrace();

              }

              Student1
studObj=new Student1();

              studObj.setStudentName(“Shiv”);

              studObj.setRollNo(1);

             

              try
{

                     objOut.writeObject(studObj);

                     objOut.flush();

                     objOut.close();

              }
catch (IOException e) {

                     //
TODO Auto-generated catch block

                     e.printStackTrace();

              }

             

       }

}


Tips about serialization

1.If class B is implementing serializable and it holds reference of class A which is not serialized then NonSerializable exception will be thrown at runtime.

2.When Object is deserialized it does not invoke the constructor. Reson is when we deserialize the Object we need to know it actual state but if constructor is called it will be changed to the default state objects. suppose

4.Static variable will neve be part of serialization.

5.How to serialize the singleton variables

@Configurable
public class NotSingleton implements Serializable {
    @Autowired
    private transient SingletonClass singleton;
   
}

6. When the serializable class extends non serializable class then the instance variable of the parent class can get the state initialized by serialized child class.

Leave a Reply

Your email address will not be published. Required fields are marked *