4 - Serialization
4 - Serialization
1. Serialization
2. Serializable Interface
3. Example of Serialization
4. Example of Deserialization
5. Serialization with Inheritance
6. Externalizable interface
7. Serialization and static data member
Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in
Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization where byte-stream is converted into an object.
The serialization and deserialization process is platform-independent, it means you can serialize an object in
a platform and deserialize in different platform.
For serializing the object, we call the writeObject() method ObjectOutputStream, and for deserialization we
call the readObject() method of ObjectInputStream class.
We must have to implement the Serializable interface for serializing the object.
It is mainly used to travel object's state on the network (which is known as marshaling).
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes so that
the objects of these classes may get a certain capability. The Cloneable and Remote are also marker
interfaces.
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
In the above example, Student class implements Serializable interface. Now its objects can be converted into
stream.
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to an OutputStream.
Only objects that support the java.io.Serializable interface can be written to streams.
Constructor
Important Methods
Method Description
1) public final void writeObject(Object obj) throws writes the specified object to the
IOException {} ObjectOutputStream.
2) public void flush() throws IOException {} flushes the current output stream.
3) public void close() throws IOException {} closes the current output stream.
ObjectInputStream class
Constructor
Important Methods
Method Description
1) public final Object readObject() throws reads an object from the input stream.
IOException, ClassNotFoundException{}
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. import java.io.*;
2. class Persist{
3. public static void main(String args[]){
4. try{
5. //Creating the object
6. Student s1 =new Student(211,"ravi");
7. //Creating stream and writing the object
8. FileOutputStream fout=new FileOutputStream("f.txt");
9. ObjectOutputStream out=new ObjectOutputStream(fout);
10. out.writeObject(s1);
11. out.flush();
12. //closing the stream
13. out.close();
14. System.out.println("success");
15. }catch(Exception e){System.out.println(e);}
16. }
17. }
success
Example of Java Deserialization
Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation
of serialization. Let's see an example where we are reading the data from a deserialized object.
1. import java.io.*;
2. class Depersist{
3. public static void main(String args[]){
4. try{
5. //Creating stream to read the object
6. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
7. Student s=(Student)in.readObject();
8. //printing the data of the serialized object
9. System.out.println(s.id+" "+s.name);
10. //closing the stream
11. in.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
211 Gabber
If a class implements serializable then all its sub classes will also be serializable. Let's see the example given
below:
1. import java.io.Serializable;
2. class Person implements Serializable{
3. int id;
4. String name;
5. Person(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
1. class Student extends Person{
2. String course;
3. int fee;
4. public Student(int id, String name, String course, int fee) {
5. super(id,name);
6. this.course=course;
7. this.fee=fee;
8. }
9. }
Now you can serialize the Student class object that extends the Person class which is Serializable. Parent
class properties are inherited to subclasses so if parent class is Serializable, subclass would also be.
If a class has a reference to another class, all the references must be Serializable otherwise serialization
process will not be performed. In such case, NotSerializableException is thrown at runtime.
1. class Address{
2. String addressLine,city,state;
3. public Address(String addressLine, String city, String state) {
4. this.addressLine=addressLine;
5. this.city=city;
6. this.state=state;
7. }
8. }
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. Address address;//HAS-A
6. public Student(int id, String name) {
7. this.id = id;
8. this.name = name;
9. }
10. }
Since Address is not Serializable, you can not serialize the instance of Student class.
If there is any static data member in a class, it will not be serialized because static is the part of class not
object.
Rule: In case of array or collection, all the objects of array or collection must be serializable. If any object is
not serialiizable, serialization will be failed.
Externalizable in java
The Externalizable interface provides the facility of writing the state of an object into a byte stream in
compress format. It is not a marker interface.
If you don't want to serialize any data member of a class, you can mark it as transient.
Now, id will not be serialized, so when you deserialize the object after serialization, you will not get the
value of id. It will return default value always. In such case, it will return 0 because the data type of id is an
integer.
SerialVersionUID
The serialization process at runtime associates an id with each Serializable class which is known as
SerialVersionUID. It is used to verify the sender and receiver of the serialized object. The sender and
receiver must be the same. To verify it, SerialVersionUID is used. The sender and receiver must have the
same SerialVersionUID, otherwise, InvalidClassException will be thrown when you deserialize the object.
We can also declare our own SerialVersionUID in the Serializable class. To do so, you need to create a field
SerialVersionUID and assign a value to it. It must be of the long type with static and final. It is suggested to
explicitly declare the serialVersionUID field in the class and have it private also. For example:
1. private static final long serialVersionUID=1L;
1. import java.io.Serializable;
2. class Employee implements Serializable{
3. private static final long serialVersionUID=1L;
4. int id;
5. String name;
6. public Student(int id, String name) {
7. this.id = id;
8. this.name = name;
9. }
10. }