Java Serialization: Class 6

3) CUSTOMIZED SERIALIZATION:

Customized Serialization is an important implementation in Java Serialization. This post is about the need for Customized Serialization. In below example code, you will also get an idea for transient keyword that we discussed in Class 3 .

Need Of Customized Serialization:
Customized Serialization includes overriding writeObject() and readObject() with our added functionality. Sometimes, we need to do something extra before saving our data to a file.



import java.io.*;

class Account implements Serializable{
 String userName = "hello";
 transient String pwd = "blog";
}

class CustomSerializeDemo{
 public static void main(String args[]) throws Exception{
  Account a1 = new Account();
  System.out.println(a1.username+"  "+ a1.pwd);
  
  //write object to a file
  FileOutputStream fos = new FileOutputStream("xyz.ser");
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  oos.writeObject(a1);

  //read Object from file
  FileInputStream fis = new FileInputStream("xyz.ser");
  ObjectInputStream ois = new ObjectInputStream(fis);
  Account a2 = (Account)ois.readObject();

  System.out.println(a2.username+"  "+ a2.pwd);
 }
}
a) In the above example before serialization Account Object can provide proper username and password. But after De-serialization Account object can provide only Username not password. This is due to declaring password variable as transient.

b) Hence during default serialization there may be chance of Loss of Information due to transient keyword.

c) To recover this loss of Information we should go for Customized Serialization.

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