Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Java Serialization: Basic concept and Implementation

In this article we will learn about the basic concepts of java serialization and its implementation in java programming.

The main purpose of java serialization is to write an object into a stream, so that it can be transported across a network and that object can be recreated again at the receiving end of the network. In practice, when there are two different parties involved, you need a protocol to rebuild the exact same object again. Java serialization API provides the same functionality to us.

Simply put, you can define java serialization as “It is a way to persist object structures”. So lets talk about how to achieve serialization in our java programs.

How we achieve serialization

When you want to serialize an object, that respective class should implement theserializable interface. It just informs the compiler that this java class can be serialized. In a object we can keep some properties away from serialization.To achieve this we can mark properties as transient. We open a stream and write the object into it. Java API takes care of the serialization protocol and persists the java object in a file.

Opposite to serialization , De-serialization is the process of getting the object back from the file to its original form.

When we serialize an object it contains information in byte form including the object data as well as its properties like what kind of data is stored in object etc. When a serialized object has been written into the file, later on it can retrieved from the file and deserialized. The process of serializing and deserializing is independent from JVM, means that java object can be serialized on one platform and it can be deserialize on other platform that is fully or partially different from first platform. This helps in persisting data into a network environment where java object are sent from one place to another or use client server communication between different java environments.With serialization it can be made sure that the data on the receiving side will be the same as the data which was actually sent.

To make a java object serializable you must implement the java.io.Serializable interface. This is the only interface which tells the java platform that the object is serializable.

Here are some uses of serialization

  • To persist data for future use.
  • To send data to a remote computer using such client/server Java technologies as RMI or socket programming.
  • To exchange data between applets and servlets.
  • To store user session in Web applications.
  • To send objects between the servers in a cluster.

Streams that contain methods for serializing and deserializing an object are:

  1. ObjectOutputStream:ObjectOutputStream class can be found in java.io package that writes primitive data types of Java objects to an OutputStream.
    Persistent storage of objects can be accomplished by using a file for the stream.Only objects that support the java.io.Serializable interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the objects fields and arrays, and the closure of any other objects referenced from the initial objects.
    The method writeObject is used to write an object to the stream. Any object, including Strings and arrays, is written with writeObject. Multiple objects can be written to the stream. The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written.
    The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The method does not need to concern itself with the state belonging to the object''''''''s superclasses or subclasses.
    Signature of method that is used to serialize an object
     public final void writeObject(Object x) throws IOException
  2. ObjectInputStream:An ObjectInputStream deserialize original data and objects previously written using an ObjectOutputStream. ObjectInputStream is used to recover those objects previously serialized.
    The method readObject is used to read an object from the stream. In Java, strings and arrays are objects and are treated as objects during serialization. When read they need to be cast to the desired type.
    The readObject method is responsible for reading and restoring the state of the object for its particular class using data written to the stream by the corresponding writeObject method. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is restored by reading data from the ObjectInputStream for the individual fields and making assignments to the appropriate fields of the object.
    Signature of method that is used to deserialize an object
     public final Object readObject() throws IOException,ClassNotFoundException

    Note: While reading an object, or deserializing , referenced class must exist. Otherwise, it will throw classsNotFoundException.

Serializing an Object

The ObjectOutputStream class is used to serialize an Object. The following SerializePerson class creates a person object and serialize it to a file.

Note: When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.

Listing 1. Create a Person object

  import java.io.*;
   
  public class Person implements java.io.Serializable
  {
     public String name;
     public String address;
     public transient int SSN;
     public int number;
  }
  

Explanation Listing 1: Here we created a person object with some public properties. We kept SSN property as transient, As we have discussed earlier, by making a property transient, will disqualify the property from being serialized.

Listing 2. Serialize an object (Person)

  import java.io.*;
   
  public class SerializePerson
  {
     public static void main(String [] args)
     {
        Person e = new Person();
        e.name = "Tom";
        e.address = "Adarsh Marg, PanchKula, Canada ";
        e.SSN = 11122333;
        e.number = 101;
        try
        {
           FileOutputStream fileOut = new FileOutputStream("/tmp/databasePerson.ser");
           ObjectOutputStream out = new ObjectOutputStream(fileOut);
           out.writeObject(e);
           out.close();
           fileOut.close();
   
           System.out.println("Serialized data is saved in /tmp/person.ser");
        }
        catch(IOException i)
        {
                           System.out.println(“Error Exists”);
        }
     }
  }  

Explanation Listing 2: Above program will create a person object and will serialize it into the databasePerson.ser file that may be referenced in later stages i.e. deserialized to get the original person object. Both streams should be closed when object has been written into the file. Like we discussed we need ObjectOutputStream to serialize an object, we created an OutputStream and passed the reference of file where person object has to be stored. We also made sure that streams should be closed after the process of serialization.

Deserializing an Object

The following DeserializePerson program deserializes the Person object created in the SerializePerson program. Here we will reference the same .ser file which we referenced when we serialized the object, since this file will have the original serialize data.

Listing 3. Deserialize an object

import java.io.*;
public class DeserializePerson
{
   public static void main(String [] args)
   {
      Person person = null;
      try
      {
         FileInputStream fileIn = new FileInputStream("/tmp/databasePerson.ser");
         ObjectInputStream inStream = new ObjectInputStream(fileIn);
         person = (Person) in.readObject();
 
         inStream.close();
         fileIn.close();
      }
      catch(IOException i)
      {
         System.out.println(“IO Error Exists”);
         i.printStackTrace();
         return;
      }
      catch(ClassNotFoundException c)
      {
         System.out.println("Person class not found here, try other options");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Person...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
    }
}

Output Listing 3:

Deserialized Person...

Name: Tom

Address: Adarsh Marg, PanchKula, Canada

SSN: 0

Number:101

Explanation Listing 3: the try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can''''''''t find a class during the deserialization of an object, it throws a ClassNotFoundException.

Note: the return value of readObject() is cast to a Person reference. The value of the SSN field was 11122333 when the object was serialized. But because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Person object is 0.

Conclusion

In this tutorial we learned the basic concept of serialization in java, and got the idea how to make an object serialize and deserialize using a person object. We also learnt how to keep some properties away from serialization using transient.



computer science Graduate :Ceo at www.gigsclerk.com (Best Marketplace to Buy and sell service online from 2$-100$ ) and www.trustingeeks.com. Interested in programming, online buissiness. Android development.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login