<<Previous Next>>
- Whenever we serialize an object, the set of all objects which are reachable from that object will be serialized automatically. This group of objects are called object graph.
- In the object graph every object should be Serializable otherwise, NotSerializableException will come.
package com.javamonkeys.serialization;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class User implements Serializable{
UserDetails ud = new UserDetails();
}
class UserDetails implements Serializable{
UserAddress ua = new UserAddress();
}
class UserAddress implements Serializable{
int uaId=10;
}
public class ObjectGraphExample {
public static void main(String[] args)throws IOException, ClassNotFoundException {
User user = new User();
FileOutputStream fiOutputStream = new FileOutputStream("D:\\serializablefile.ser");
ObjectOutputStream oStream = new ObjectOutputStream(fiOutputStream);
oStream.writeObject(user);
FileInputStream fileInputStream = new FileInputStream("D:\\serializablefile.ser");
ObjectInputStream oInputStream = new ObjectInputStream(fileInputStream);
User usr = (User)oInputStream.readObject();
System.out.println(usr.ud.ua.uaId);
}
}
Note: In the
above example User, UserDetails and UserAddress should be serialized otherwise
we will get NotSerializableException.

No comments:
Post a Comment