Straight from the Heart

Some bits and pieces related to java Serialization

Posted on: October 23, 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:

1 Response to "Some bits and pieces related to java Serialization"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Translator

a

The Calendar..तारीख

October 2008
M T W T F S S
« Sep   Nov »
 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

पन्ना

हिसाब-किताब

  • 37,617 hits

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

Ceannabeinne

Cuckoo, Cuckoo

All the Small Mistakes

The Old Teahouse in Pengzhen Town, Chengdu

Kestrel      (Falco tinnunculus)

American Crow

Sony A7 MII + Zeiss Sonnar 50/1.5 ZM

Einsam

sparkles

Tunnel View Sunset

More Photos

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

website statistics

Rumbling of Mind

  • Sushil Kumar has won his second Olympic medal, become the first Indian to win two individual Olympic medals for India. Respect. 4 years ago
  • Satyamev Jayate-A great initiative by Aamir Khan & company....must watch on star plus/DD National every Sunday 11:00 AM 4 years ago
  • @sujeetkant number is changed..sent on your linkedin.. 4 years ago
  • @sujeetkant dude I m fine..howz life at you end ..long time 4 years ago
  • In real bad mood.. :( Banged my car today.. 4 years ago

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

Top Clicks..पसंदीदा

  • None

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

U come from..

%d bloggers like this: