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.

 

Output:

 

Common errors encountered during Serialization:

  1. 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.
  2. 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.
  3. 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.

Sushil Singh

My name is Sushil Kumar Singh. I’m the founder, designer and editor of this blog. I would love to hear your thoughts and opinions on my articles directly. You can write to me at sushilsingh@learningsolo.com. I’ll try to respond as soon as possible. Alternatively, you can connect with me directly on linkedin or github or Facebook.

Leave a Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of