Java Serialization: Class 7

Implementation of Customized serialization:
We already discussed the need for Customized Serialization in our previous class. Now we will discussed, how we can implement it and use it in our java code.

We can implement Customized Serialization by using following 2 methods:

a) private void writeObject(ObjectOutputStream os) throws Exception

i) This method will be executed automatically at the Time of Serialization.
ii) Hence while performing Serialization if we want to do any extra work we have to write corresponding Code in this method.

b) private void readObject(ObjectInputStream is) throws Exception

i) This method will be executed at the time of De-serialization.
ii) Hence while performing De-serialization if we want to do Extra work we have to write corresponding code in this method only.



import java.io.*;

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

 //customized writeObject
 private void writeObject(ObjectOutputStream os){
  os.defaultWriteObject();
  String epwd = "123" + pwd;
  os.writeObject(epwd);
 }

 //customized readObject
 private void readObject(ObjectInputStream is){
  is.defaultReadObject();  
  String epwd = (String) is.readObject();
  pwd = epwd.substring(3);
 }
}

class CustomSerializeDemo{
 public static void main(String args[]){
  Account a1 = new Account();
  System.out.println(a1.username+"  "+a1.pwd);
  
  FileOutputStream fos = new FileOutputStream(""xyz.ser");
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  oos.writeObject();
  
  FileInputStream fis = new FileInputStream("xyz.ser");
  ObjectInputStream ois = new ObjectInputStream(fis);
  Account a2 = (Account)ois.readObject();
  
  System.out.println(a2.username+ "  "+ a2.pwd);
 } 
}

Note:
a) the above methods are callback methods because these methods will be executed automatically by JVM.
b) While performing which object Serialization we have to do extra work, in the corresponding class we have to define above methods.
ex: For example while performing Account Object Serialization if we required to do extra work , then in Account Class we have to define methods.figure:

in the above figure, as we have defined password variable in our Account class as transient. Therefore, we are not able to store our password in serialized file. so in our customized Serialization, we are going to implement some code in our writeObject() callback methods(Methods which are automatically called by JVM are called callback methods) and we will write password individually in that file with some encryption and will read from readObject custom code and assign it to our variable.

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