Wednesday, 3 September 2014

Continue previous post

Employee.java
import java.io.*;
 
class Employee implements Externalizable{
 
  String ename;
  int age;
  double salary;
 
    //0-arg constructor
    public Employee()    {
        System.out.println("Employee()");
    }
 
    //parameterized constructor
    public Employee(String name, int age, double salary) {
        System.out.println("Employee(-,-,-)");
        ename = name;
        this.age = age;
        this.salary = salary;
    }
 
    //Just prints everything
    public String toString() {
        return "Emp Name::"+ename+" Emp Age::"+age+"
                    Emp Sal::"+salary;
    }
 
    //Here we have serialized only 2 properties,we have not serialized salary
    public void writeExternal(ObjectOutput out) throws IOException  {
        out.writeObject(ename);
        out.writeInt(age);
    }
    //Here we have mentioned what we want to deserialize,I am intrested to deserialize only ename
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        ename = (String) in.readObject();//it will be deserialized and stored in ename property
    }
 
}
 ExternalizableDemo.java
public class ExternalizableDemo {
    public static void main(String args[])throws Exception {
 
        //parameterized constructor is called
        Employee emp=new Employee("Satya",23,15000.00);
 
        //Serialization process
        FileOutputStream fos = new FileOutputStream("d:/myFile.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(emp);
        oos.flush();
        oos.close();
 
        // Object deserialization
        FileInputStream fis = new FileInputStream("d:/myFile.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);
 
        //0-args constructor is called
        Employee emp2 = (Employee)ois.readObject();
        ois.close();
        System.out.println("Details ::: " + emp2);  //toString() is called,which prints the details
        //Note that only name is deserialized
    }
}//class
Note :-
To create Employee object,we are using parameterized constructor,
But to deserialize,JVM automatically looks for 0-args constructor.
Hope this article proves to be valuable one.
Any query/mistakes,we would like to hear from you.

No comments:

Post a Comment