Java Serialization: Class 5

2) OBJECT GRAPH IN SERIALIZATION:



1) Whenever we are serializing an Object the Set of all objects which are reachable from that Object will be serialized Automatically. This group of Objects is nothing but Object Graph.

2) In Object Graph, every object should be serializable. If at least one Object is not Serializable then we will get Runtime Exception saying NotSerializableException.

import java.io.*;

class Dog implements Serializable{
 Cat c = new Cat();
}
class Cat implements Serializable{
 Rat r = new Rat();
} 
class Rat implements Serializable{
 int j=20;
}

class SerializeDemo{
 public static void main(String args[]){
  Dog d1 = new Dog();
 
  FileOutputStream fos = new FileOutputStream("xyz.ser");
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  oos.writeObject(d1);

  FileInputStream fis = new FileInputStream("xyz.ser");
  ObjectInputStream ois = new ObjectInputStream(fis);
  ois.readObject(d1);
  
  System.out.println(d2.c.r.j); //20 
 }
}

In the above example whenever we are serializing Dog Object automatically Cat and Rat Objects will be serialized, because these are part of Object Graph of Dog Object.

Among Dog, Cat and Rat if at least one Object is non serializable then we will get Runtime Exception saying NotSerializableException.

Share on Google Plus

About Unknown

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 comments:

Post a Comment