Friday 28 October 2016

Java Source World: Serialization in Java

Serialization in Java | Java Source World

                                                           Javasourceworld                         A Java quick reference blog



Serialization in Java | Why we need to implement Serializable interface in java 


java.io.Serializable Interface :
This interface is used to mark serialization and deserialization of an object. Serialization is a process in which an object state is read from memory and written into a file or a database. Deserialization is a process in which an object state is read from a file or a database and written back into memory. Any class which wants it’s object to be eligible for serialization and deserialization must implement Serializable interface.

Why we need to implement Serializable interface:



Lets go through an example by the way we will understand why we need to implement Serializable interface in java.

For example I have a class Employee.java which is having properties and their getter and setter methods.

 Employee .java

package com.core.serialization;
import java.io.Serializable;

public class Employee implements Serializable{
                private int employeeID;
                private String firstName;
                private String lastName;
                 private static final long serialVersionUID = 1L;
                public int getEmployeeID() {
                                return employeeID;
                }
                public void setEmployeeID(int employeeID) {
                                this.employeeID = employeeID;
                }
                public String getFirstName() {
                                return firstName;
                }
                public void setFirstName(String firstName) {
                                this.firstName = firstName;
                }
                public String getLastName() {
                                return lastName;
                }
                public void setLastName(String lastName) {
                                this.lastName = lastName;
                }
}

Now I want to write the state of an Employee object to a file. To do that I need to use FileOutputStream and ObjectOutputStream to wrirte the state of an object to a file.

   SerializationClass.java

               package com.core.serialization;
               import java.io.FileNotFoundException;
                import java.io.FileOutputStream;
                import java.io.IOException;
                import java.io.ObjectOutputStream;

                public class SerializationClass {
                         public static void main(String[] args) {
                                            Employee emp = new Employee();
                                             emp.setEmployeeID(1);
                                                emp.setFirstName("First Name");
                                                emp.setLastName("Last Name");
                                               
                              try {
                                    FileOutputStream fout = new FileOutputStream("C:/Users/Desktop/employee.txt");
                                           try {
                                                         ObjectOutputStream oout = new ObjectOutputStream(fout);
                                                                                oout.writeObject(emp);
                                                                                oout.close();
                                                                                fout.close();
                                                              System.out.println("Serialization data is saved in employee.txt");
                                                                } catch (IOException e) {
                                                                                e.printStackTrace();
                                                                }
                                                } catch (FileNotFoundException e) {
                                                                e.getMessage();
                                                }
                                }
                }

Now we will check the output of the above code by running it.
Console: Serialization data is saved in employee.txt

Now we will try to deserialize the object, before that just modify the Employee.java, just add one another extra property to Employee.java and remove the implements Serializable.
Just assume added the fallowing property to the Employee.java and removed the implements keyword.
private String cityName;

Now we modified the object which is already serialized before deserializing it.

Now we will try to deserialize the object.

To do that we need to read the file using FileInputStream and ObjectInputStream needs be used to read the object.

 DeSerializationClass.java

                package com.core.serialization; 
                import java.io.FileInputStream;
                import java.io.FileNotFoundException;
                import java.io.IOException;
                import java.io.ObjectInputStream;

                public class DeSerializationClass {
                                public static void main(String[] args) {
                                                Employee emp = null;
                                                try {
FileInputStream fis = new FileInputStream("C:/Users/Desktop/employee.txt");
try {
    ObjectInputStream ois = new ObjectInputStream(fis);
           emp = (Employee)ois.readObject();
 System.out.println("Employee: "+emp.getEmployeeID()+"\n"+emp.getFirstName());
catch (IOException e) {
              e.printStackTrace();
catch (ClassNotFoundException e) {
                e.printStackTrace();
                }
catch (FileNotFoundException e) {
                  e.printStackTrace();
}
                                               
                                }
                }

Now we will run the above code and see the output.
Console:
Output:
java.io.InvalidClassException: com.core.serialization.Employee; com.core.serialization.Employee; class invalid for deserialization
                at java.io.ObjectStreamClass.checkDeserialize(Unknown Source)
                at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
                at java.io.ObjectInputStream.readObject0(Unknown Source)
                at java.io.ObjectInputStream.readObject(Unknown Source)
                at com.core.serialization.DeSerializationClass.main(DeSerializationClass.java:15)
Caused by: java.io.InvalidClassException: com.core.serialization.Employee; class invalid for deserialization
                at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
                at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
                at java.io.ObjectInputStream.readClassDesc(Unknown Source)
                ... 4 more


So, we got java.io.InvalidClassException, becauase the Employee object is got modified and not implemented the Serializable interface. 

Now we will add implement Serializable interface to the Employee.java and run the same program, then we will get the fallowing console output.
Output:
Employee: 1
First Name

Code is got executed and produced the output, hence to avoid class cast exceptions while deserializing and to maintain the state of an object we should implement Serializable itnerface.



Also read:
Join() Method in Multi Threading
Equals and Hashcode
What will happen if equals and hashcode not overridden
What are marker interfaces in java
Differences between Aggregation and Composition




                                                           Javasourceworld                         A Java quick reference blog

No comments:

Post a Comment