Java serialization is a process that writes an object's state into a byte stream. It is primarily used in systems such as Hibernate, RMI, JPA, EJB, and JMS.
The inverse procedure is called deserialization where the byte-stream is transformed into an object. The method of serialization and deserialization is platform-independent, meaning you can serialize an object on a platform and deserialize it on various platforms.
To serialize the object, we call the Object Output Stream method write Object(), and we call the Object Input Stream class method read Object() for deserialization.
To serialize the object, we need to implement the Serializable interface.
It is primarily used to travel the state of the objecton the network (known as marshaling).
java.io.Serializable interface
Serializable is a marker interface (data member and method are not available). It is used to "label" Java classes so that these classes ' objects can acquire a certain capacity. Also, marker interfaces are Cloneable and Remote.
The class whose object you want to persist must implement it.
By default java.io.Serializable interface is implemented by the String class and all wrapper classes.
In the instance below, serializable interface is implemented by the student class. Now it is possible to convert its objects into stream.
import java.io.Serializable; public class Student implements Serializable{ int studentId; String studentName; public Student(int istudentId, String studentName) { this.studentId = studentId; this.studentName = studentName; } }
The Object Output Stream class is used to write primitive data types and Output Stream to Java objects. It is possible to write to streams only objects that support the java.io.Serializable interface.
Constructor:
public ObjectOutputStream(OutputStream out) throws IOException {} | It creates an ObjectOutputStream that writes to the specified OutputStream. |
Important Methods:
Method | Description |
---|---|
public final void writeObject(Object obj) throws IOException {} | It writes the specified object to the ObjectOutputStream. |
public void close() throws IOException {} | It closes the current output stream. |
public void flush() throws IOException {} | It flushes the current output stream. |
An Object Input Stream uses an Object Output Stream to deserialize objects and primitive information/data written.
Constructor
public ObjectInputStream(InputStream in) throws IOException {} | It creates an ObjectInputStream that reads from the specified InputStream. |
Important Methods
Method | Description |
---|---|
public void close() throws IOException {} | It closes ObjectInputStream. |
public final Object readObject() throws IOException, ClassNotFoundException{} | It reads an object from the input stream. |
In this instance, we will serialize the student class object. Object Output Stream class method write Object() offers the features for serializing the object. We save the object status in the file called test.txt.
import java.io.*; class Persist{ public static void main(String args[]){ try{ Student s1 =new Student(561,"Rahul"); //Creating stream and writing the object FileOutputStream fout=new FileOutputStream("test.txt"); ObjectOutputStream out=new ObjectOutputStream(fout); out.writeObject(s1); out.flush(); //closing the stream out.close(); System.out.println("success"); }catch(Exception e){System.out.println(e);} } }
The method of reconstruction of the object from the serialized state is deserialization. It's the reverse procedure of serialization. Let's look at an instance where we read a deserialized object's information.
import java.io.*; class Depersist{ public static void main(String args[]){ try{ //Creating stream to read the object ObjectInputStream in=new ObjectInputStream(new FileInputStream("test.txt")); Student s=(Student)in.readObject(); //printing the data of the serialized object System.out.println(s.id+" "+s.name); //closing the stream in.close(); }catch(Exception e){System.out.println(e);} } }
Output:
561 Rahul
You can mark it as transient if you don't want to serialize any data member of a class.
class Student implements Serializable{ transient int studentId; String studentName; public Student(int studentId, String studentName) { this. studentId = studentId; this. studentName = studentName; } }
Now, studentId won't be serialized, so you won't get the Id value if you deserialize the object after serialization. It always returns the default value. It will return 0 in such a case because the studentId data type is an integer.
The runtime serialization process associates an Id with each Serializable class called SerialVersionUID. It is used to check the serialized object's sender and receiver. The sender must be the same as the receiver. SerialVersionUID is used to check this. The sender and receiver must have the same SerialVersionUID, otherwise, InvalidClassException will be thrown when deserializing the object. We can declare our own SerialVersionUID in the Serializable class as well. To do this, it is necessary to create a SerialVersionUID field and assign a value to it. It must be static and final in the long type. It is suggested that the serialVersionUID field is explicitly declared in the class and that it be private as well.
Example: privatestaticfinallong serialVersionUID=5L;
Keep sharing blogs like this one; they are quite good. You have given everyone in this blog access to a wealth of information.
Thank you for your valuable information.
Thank you for this wonderful article!
This article was really helpful to me, thank you!
super article!
Leave a Reply
Your email address will not be published. Required fields are marked *