I will explain you what is java serialization, then provide you with a sample for serialization. Finally most importantly, lets explore what is inside a serialized object and what it means. That is internals of java serialization and how does it works. If you want to have your own implementation of java serialization, this article will provide you with a good platform to launch.
What is Java Serialization?
Primary purpose of java serialization is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again. When there are two different parties involved, you need a protocol to rebuild the exact same object again. Java serialization API just provides you that. Other ways you can leverage the feature of serialization is, you can use it to perform a deep copy.
Why I used ‘primary purpose’ in the above definition is, sometimes people use java serialization as a replacement for database. Just a placeholder where you can persist an object across sessions. This is not the primary purpose of java serialization. Sometimes, when I interview candidates for Java I hear them saying java serialization is used for storing (to preserve the state) an object and retrieving it. They use it synonymously with database. This is a wrong perception for serialization.
How do you serialize?
When you want to serialize an object, that respective class should implement the marker interface serializable. It just informs the compiler that this java class can be serialized. You can tag properties that should not be serialized as transient. You open a stream and write the object into it. Java API takes care of the serialization protocol and persists the java object in a file in conformance with the protocol. De-serialization is the process of getting the object back from the file to its original form.
Here protocol means, understanding between serializing person and de-serializing person. What will be the contents of file containing the serialized object? This serves as a guideline to de-serialize. Have a look at the following sample and how its serialized file looks.
Lets take example of Employee Object which has couple of properties. We want to serialize employee object.
package serializationdemo;
import java.io.Serializable;
class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private String eName;
private String eId;
//Getters and setters and constructor
Employee(String a, String b){
this.eName = a;
this.eId = b;
}
}
Java Calss which serializes the employee object and write into the file.
package serializationdemo;
import java.io.*;
public class EmployeeSerialDemo {
public static void main(String[] args) {
Employee c = new Employee("Suresh", "E123");
File outFile = new File("empSerial.ser");
try {
FileOutputStream fs = new FileOutputStream(outFile);
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
After running above EmployeeSerialDemo class we get "empSerial.ser" file created which can be send across to network or database for desreialze at later stage. Below class is implementation of deserialization process where we recreate the employee object from file.
package serializationdemo;
import java.io.*;
public class EmployeeDeserialDemo {
public static void main(String[] args) {
File ReadFile = new File("empSerial.ser");
try {
FileInputStream fis = new FileInputStream(ReadFile);
ObjectInputStream ois = new ObjectInputStream(fis);
Employee e = (Employee) ois.readObject();
System.out.println("Deserialized Employee name= "+ e.geteName());
System.out.println("Deserialized Employee ID= "+ e.geteId());
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
OUTPUT:
Deserialized Employee name= Suresh
Deserialized Employee ID= E123
Serialization with Composition(Has-A) relationship:
Composition (HAS-A) simply mean use of instance variables that are references to other objects. Let’s understand if Employee class has department object reference and if department class does not implement Serializable interface then we have to declare department reference as transient or we will get exception while calling serialize method.
Serialization with Inheritance relationship:
If a super class is Serializable, then according to normal Java interface rules, all subclasses of that class automatically implement Serializable implicitly. In other words, a subclass of a class marked Serializable passes the IS-A test for Serializable, and thus can be saved without having to explicitly mark the subclass as Serializable.
If you serialize a collection or an array, every element must be Serializable. A single non-serializable element will cause serialization to fail if not declared transient.
Serialization Is Not for Static variables
Finally, you might notice that we've talked ONLY about instance variables, not static variables. That is because static variables are not part of instance state, so not part of Serialization process.