Tuesday 19 February 2019

Serialization and De-Serialization

Serialization and De-Serialization
When you create a class, you may create an object for that particular class and once we execute/terminate the program, the object is destroyed by itself via the garbage collector thread.
What happens if you want to call that class without re-creating the object? In those cases, what you do is use the serialization concept by converting data into a byte stream.
Object Serialization is a process used to convert the state of an object into a byte stream, which can be persisted into disk/file or sent over the network to any other running Java virtual machine. The reverse process of creating an object from the byte stream is called deserialization. The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform.

How to Make a Java Class Serializable?

Serializability can be enabled in your Java class by implementing the java.io.Serializable interface. It is a marker interface that means it contains no methods or fields and only serves to identify the semantics of being serializable.

What if We Are Trying to Serialize a Non-Serializable Object?

We will get a RuntimeException saying: Exception in thread "main" java.io.NotSerializableException: java.io.ObjectOutputStream.

What Is the serialVersionUID?

SerialVersionUID is an ID, which is stamped on an object when it gets serialized usually with the hashcode of the object. We can find serialVersionUID for the object by the serialver tool in Java.
Syntax: serialver classname
SerialVersionUID is used for version control of an object. The consequence of not specifying serialVersionUID is that when you add or modify any field in the class, then the already-serialized class will not be able to recover because the serialVersionUID was generated for the new class and the old serialized object will be different. The Java serialization process relies on correct serialVersionUID for recovering the state of the serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch.

Transient Keyword

The transient modifier/keyword is applicable only for variables but not for methods and classes.
At the time of serialization, if we don't want to serialize the value of a particular variable to meet security constraints, then we should declare that variable as transient.
While performing serialization, the JVM ignores the original value of the transient variable and save default value to the file. Hence, transient means not to serialize.

Transient Vs. Static

A static variable is not part of an object state, and hence, it won't participate in serialization. Due to this declaring static variable as transient, there is no use.

Final Vs. Transient

Final variables will be participated in serialization directly by the value. Hence, declaring a final variable as transient causes no impact.
Now, let us consider a program that shows serialization and de-serialization in Java.
This POJO class Employee implements the Serializable interface:
package com.java.serialization;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private String serializeValueName;
private transient int nonSerializeValueSalary;
public String getSerializeValueName() {
return serializeValueName;
}
public void setSerializeValueName(String serializeValueName) {
this.serializeValueName = serializeValueName;
}
public int getNonSerializeValueSalary() {
return nonSerializeValueSalary;
}
public void setNonSerializeValueSalary(int nonSerializeValueSalary) {
this.nonSerializeValueSalary = nonSerializeValueSalary;
}
@Override
public String toString() {
return "Employee [serializeValueName=" + serializeValueName + "]";
}
}

The following SerializingObject program instantiates an Employee object and serializes it to a file.
package com.java.serialization;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerializingObject {
public static void main(String[] args) {
Employee employeeOutput = null;
FileOutputStream fos = null;
ObjectOutputStream oos = null;
employeeOutput = new Employee();
employeeOutput.setSerializeValueName("Aman");
employeeOutput.setNonSerializeValueSalary(50000);
try {
fos = new FileOutputStream("Employee.ser");
oos = new ObjectOutputStream(fos);
oos.writeObject(employeeOutput);
System.out.println("Serialized data is saved in Employee.ser file");
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
} 
}
}

Output :
Serialized data is saved in Employee.ser file.

The following DeSerializingObject program deserializes the Employee object created in the SerializingObject program.
package com.java.serialization;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class DeSerializingObject {
public static void main(String[] args) {
Employee employeeInput = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("Employee.ser");
ois = new ObjectInputStream(fis);
employeeInput = (Employee)ois.readObject();
System.out.println("Serialized data is restored from Employee.ser file");
ois.close();
fis.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} 
System.out.println("Name of employee is : " + employeeInput.getSerializeValueName());
System.out.println("Salary of employee is : " + employeeInput.getNonSerializeValueSalary());
}
}

Output:
Serialized data is restored from Employee.ser file
Name of employee is : Aman
Salary of employee is : 0

No comments:

Post a Comment

Unity Top Download

Latest post

An Introduction to Hybris from basics

An Introduction to Hybris from basics:  -- ecommerce site and PCM(Product content Management) solutions. eg. croma website.  -- having sear...

Popular posts