Search This Blog

Java- Serialization

         Serialization is a mechanism provided by java which can be used to represent an object in byte format, which include object’s data as well as information about object’s data type and also the data type stored in that object.
  
 For a class to to be serializable :
  •    It should extend “java.io.Serializable”
  •    All the fields in the class must be able to be serialized. In case there is some data which need not to be serialized should be marked as “transient”.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.


Serialization of Object :

Step1 : The object which needs to serialized should implement Serializable interface (eg: Customer.java)
Step2 : Write a class which actually serialize the object and save it in file on disk.(eg : SerializeObject.java)




On executing the SerializeObject.java , we found Customer.ser file which includes the Customer object information @ specified location.
 
         
                 

Deserialization of Object:

We will write a java class which will read the serialized object and will print the object details.In this tutorial we will read the serialized objec that we have created in above mentioned section (Customer.ser)


Execution of this class file will give us below mentioned result










Note that in the output, value of the Customer id is 0 whereas we had set it as "123". The reason behind it is that we had mentioned "id" as a transient variable.Which means while serializing value of "id" didn't get serialized to file.This feature is helpful when you don't want to save some specific data  eg: SSN, Credit card number etc


No comments:

Post a Comment