Serialization in Java
Serialization in Java
Overview
Serialization in java is a mechanism of writing the state of an object into a byte stream.
Serialization is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies. The reverse operation of serialization is called deserialization.
Advantage of Java Serialization
Serialization is used to send object’s state on the network (known as marshaling).
[java]java.io.Serializable interface[/java]
Serializable is a marker interface (has no data member and method). It is used to “mark” java classes so that objects of these classes gets certain capability. The Cloneable and Remote are also marker interfaces.
It must be implemented by the class whose object you want to persist.
The String class and all the wrapper classes implements java.io.Serializable interface by default.
Example of Java Serialization
In this example, we are going to serialize the object of Student class. The writeObject() method of ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the object in the file named f.txt.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.io.*; class Persist{ public static void main(String args[])throws Exception{ Student s1 =new Student(211,"ravi"); FileOutputStream fout=new FileOutputStream("f.txt"); ObjectOutputStream out=new ObjectOutputStream(fout); out.writeObject(s1); out.flush(); System.out.println("success"); } } |
Output:
1 |
success |
Common errors encountered during Serialization:
- NotSerializableException: This happens when the class or its Super class doesn’t implements Serializable interface. So we need to ensure that the hierarchy implements Serializable interface.
- InvalidClassException : When an object is serialized, the serialVersionUID is serialized along with the other contents. Later when that is deserialized, the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class. If the numbers do not match then, InvalidClassException is thrown.
- ClassNotFoundException: When the deserialization happens, JVM tries to load the class with the same SerialVersionUID as present in serialized stream and if the class is not available then the JVM throws ClassNotFoundException.