- It is a process of converting the state of an object into a byte stream
- A class must implement Serializable interface present in java.io package in order to serialize its object
- Serializable is the example of Marker Interface
- It is used in Hibernate,RMI, JPA, EJB and JMS..
Advantages of
Serialization
- To save/persist state of an object.
- To move an object across a network.
Points to
remember
- If a parent class has implemented Serializable interface then child class doesn’t need to implement it (Imp point).
- Only non-static data members are used in Serialization process.
- Static data members are not saved in Serialization.
- Constructor of object is never called when an object is deserialized.
Example:
import java.io.*;
public class Employee
implements Serializable
{
String name;
int EmpId;
static String company;
Employee (String nm, int Ed,
String c)
{
this.name = nm;
this.EmpId =Ed;
this.contact = c;
}
}
class Test
{
public static void main(String[] args)
{
try
{
Employee emp = new Employee ("Dipak",
105, "LearingPoint92");
FileOutputStream fos = new
FileOutputStream("emp.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(emp);
oos.close();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Explanation:
Object of Employee class is serialized using
writeObject()
method and written to emp.txt
file.
Deserialization
The reverse operation of
serialization is called deserialization.
Converting byte
stream into the state of an object is called deserialization
import
java.io.* ;
public class
DeserializationDemo
{
public static void main(String[] args)
{
Employee emp=null;
try
{
FileOutputStream fos = new FileOutputStream("emp.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
emp=(Employee)oos.readObject();
}
catch (Exception e)
{
e.printStackTrace();
System.out.println(emp.name);
System.out. println(emp.EmpId);
System.out.println(emp.company);
}
}
Output:
Dipak
105
null
Company field is null because,
it was declared as static and as we have pointed earlier static fields does not
get serialized.
NOTE: Static members are never serialized
because they are connected to class not object of class.
No comments:
Post a Comment