Straight from the Heart

Archive for October 2008


One of the interesting concepts of the java is Serialization. We all know in java we can create reusable objects in the memory as long as the JVM is in the running state. Serialization provides the flexibility of object persistence beyond JVM lifecycle.

 

In the short serialization is the process of saving state of an object in a file. For that purpose, that object should implement the Serializable interface; same we are doing in the class Sedan.

 

A simple example of serialization is as follows-

 

public class Sedan implements Serializable{

private double price=44000.0;

 

public Sedan(double price){

      this.price=price;

}

public double getPrice() {

      return price;

}

 

public void setPrice(double price) {

      this.price = price;

}

}

 

public class SerializeSedan {

      public static void main(String[] args) {

 

            Sedan sedanObject= new Sedan(55000.0);

            FileOutputStream outputStream;

            try {

                  System.out.println(sedanObject.getPrice());

                  outputStream = new FileOutputStream(“myTestFile.ser”);

                  ObjectOutputStream obystr= new ObjectOutputStream(outputStream);

                  obystr.writeObject(sedanObject);

                  obystr.close();

 

                  FileInputStream in= new FileInputStream(“myTestFile.ser”);

                  ObjectInputStream objin= new ObjectInputStream(in);

                  try {

                        sedanObject=(Sedan)objin.readObject();

                        System.out.println(sedanObject.getPrice());

                  } catch (ClassNotFoundException e) {

                        e.printStackTrace();

                  }

                  objin.close();

            } catch (FileNotFoundException e) {

                  e.printStackTrace();

            }catch (IOException exp) {

                  exp.printStackTrace();

            }

      }

}

 

 

Run the SerializeSedan Class. The output will be-

Before- 55000.0

After- 55000.0

 

 

Now change the Sedan a bit.

 

 

public class Sedan extends Car implements Serializable { private double price=44000.0;

private Gearbox gearbox=null;

 

public Sedan(double price, Gearbox gearbox){

      this.price=price;

      this.gearbox=gearbox;

}

public double getPrice() {

      return price;

}

 

public void setPrice(double price) {

      this.price = price;

}

public Gearbox getGearbox() {

      return gearbox;

}

public void setGearbox(Gearbox gearbox) {

      this.gearbox = gearbox;

}

}

 

public class Car implements Serializable{

      private int yearModel=2005;

 

      public int getModelyear() {

            return yearModel;

      }

 

      public void setModelyear(int modelyear) {

            this.yearModel = modelyear;

      }

     

}

 

public class Gearbox {

 

private int gearCaseNumber=0;

 

public int getGearCaseNumber() {

      return gearCaseNumber;

}

 

public void setGearCaseNumber(int gearCaseNumber) {

      this.gearCaseNumber = gearCaseNumber;

}

 

}

 

Now we have an instance variable of type Gearbox, now for serialization of Sedan object, Gearbox should also implement Serializable interface.

And what if the Gearbox itself had references to other objects? This gets fairly complex. If it were up to the programmer to know the internal structure of each object the Sedan referred to, so that the programmer could be sure to save all the state of all those objects…..Which is really difficult to achieve. The good thing about java is – java Serialization mechanism internally take care of the whole object graph. In the case, we are unaware of the structure of Gearbox class or Gearbox is not implementing Serializable interface and we are not able to the change code also.

We can create a sub class of Gearbox, which eventually implement Serializable interface and what if Gearbox is final class.

 

Here transient modifier comes in picture. Transient is used to skip an instance variable during serialization.

 

public class Sedan implements Serializable{

private double price=44000.0;

private transient Gearbox gearbox=null;

 

Now during serialization, variable gearbox will be skipped.  We are skipping the gearbox variable so we can not read the gearCaseNumber while reading the state of the object as it will throw a null pointer error while getting Gearbox object.

 

Java provides solution for that problem also, for that some change requires in the Sedan class.  Add these two methods in Sedan class and these methods will solve the purpose.

 

private void writeObject(ObjectOutputStream os)

      {                          

            try {

                  os.defaultWriteObject();                         

                  os.writeInt(gearbox.getGearCaseNumber());           

            } catch (Exception e) { e.printStackTrace(); }

      }

 

 

      private void readObject(ObjectInputStream is) {

            try {

                  is.defaultReadObject();                            

                  gearbox = new Gearbox(is.readInt());             

            } catch (Exception e) {

                  e.printStackTrace();

            }

      }

 

Now output is-

68686After- 55000.0

68686After- 55000.0

Here, when you invoke defaultWriteobject() from within writeObject() you’re telling the JVM to do the normal serialization process for this object. When implementing writeObject(), you will typically request the normal serialization process, and do some custom writing and reading too. Please read sun java doc for the clear understanding of methods related to ObjectOutputStream class.

This was just an introduction of the Serialization, Lots more to follow. Hope it helps.

Cheers,

Manu

Tags:

Translator

a

The Calendar..तारीख

October 2008
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

गुफ्तुगू ….

Sindhu on How to integrate Sonar with…
Naga Anji on EMMA: a free Java code coverag…
Manu on Hiring
jarvarm on Hiring
Manu on Hiring

पन्ना

हिसाब-किताब

  • 40,681 hits

Tashveerein.......तसवीरें

Thanks for the Visit…आने का शुक्रिया

website statistics

Aaate-Jaate..आते-जाते

Top Clicks..पसंदीदा

  • None

The Selected One’s..चुनिन्दा

U come from..