Serialization with code example:
To get a better understanding of how serialization implementation works, let's check out the below example.
import java.io.*; //file io needed for below Methods Class Dog implements Serializable{ int i=10; int j =20; } Class SerializeDemo{ public static void main(String args[]) throws Exception{ //Serialization Dog d1 = new Dog(); FileOutputStream fos = new FileOutputStream("abc.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.WriteObject(d1); //De Serialization FileInputStream fis = new FileInputStream("abc.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Dog d2 = (Dog) ois.readObject(); System.out.println(d2.i + " " +d2.j); } }Note:
a) For implementing Serialization and deserialization on any class we need to implement Serializable Interface. If we do not implement Serialzable class than at compile time we will not get any error but at run time:
RUNTIME EXCEPTION: non serializable exception
b) If abc.ser is not present than FileOutputStream will create it.
Conclusion:
a) Serializable present in io package
b) Serializable interface does not contain any method. these interfaces are called marker interface.
0 comments:
Post a Comment