| Introduction | | | | /* |
| At the time of development, sometimes it is necessary | | | | * Code to deserialize the object |
| to store the state of the object in the file system. | | | | */ |
| Some objects may or may not be stored in the file | | | | ObjectInputStream oin = new ObjectInputStream( new |
| system depending upon the structural intensity of the | | | | FileInputStream("D:/test.ser")); |
| object graph. In this article, I will focus on two major | | | | Emp emp1 = ( Emp )oin.readObject(); |
| aspects of the object persistence. Before going to this | | | | System.out.println("Emp age----"+emp1.getAge()); |
| subject, I would like to tell you about the significance of | | | | System.out.println("Emp Name----"+emp1.getName()); |
| the object persistence. Object persistence | | | | }catch( Exception e ) |
| presupposes the state of the object in the file system. | | | | {e.printStackTrace(); |
| In this matter you can make argument regarding | | | | } |
| object persistence in the database, which hibernate | | | | } |
| does. But so far this article is concerned I will give | | | | } |
| glimpse on persistence in the file system for all | | | | You can run the above code in your editor to test the |
| convenience. The state of object signifies the | | | | functionalities relating to serialization. |
| attributes or properties of the object in the broader | | | | Now I put forward some cases for seriliazation. |
| sense. The object graph represents the internal | | | | Case-1: |
| morphological structure of the object. So persisting | | | | If your object does not implement Serializable interface, |
| object means, you are going to store all the internal | | | | In order to serialize an object, it is a must that the class |
| changed structure of the object. | | | | must implement seriliazable interface. This is the |
| Technicalities | | | | required principle of serilization. Oterwise it will throw |
| There are several ways you can persist the state of | | | | NotSerializationException. |
| the object. You can take help from Java IO system to | | | | There is another way, if your class does not |
| store the object in the file system. However there are | | | | implement Serilizable interface, you have to declare the |
| convenient approaches you can meet your | | | | object as transient. So that that object state will not be |
| expectations in this regard. One way is the textual | | | | persisted. |
| representation of the object graph in the file system | | | | Case-2: |
| and another way is the binary representation of the | | | | In case of inheritance, your super class does not |
| object graph. These ways are very much convenient | | | | implement Serializable interface and sub class also |
| and easy from the view point of development. You | | | | does not. |
| can achieve the textual representation of the object | | | | In this case serilization will not happen . If you are |
| graph using XMLEncoder and you can achieve the | | | | interested to store the all the properties of the object |
| binary representation of the object graph using java | | | | you can go for XMLEncoder and XMLDecoder as I |
| object serialization process. Let me explain the two | | | | have alredy explained you. |
| approaches below. | | | | Case-3: |
| Persistence using XMLEncoder | | | | In case of inheritance, your class implements |
| XMLEncoder class is an approach to persist the | | | | Serializable interface and sub class does not. |
| object graph in an XML document or simply in an XML | | | | In this case, you should not worry about it, seriliazation |
| file. It provides the flexibility of storing the object as a | | | | happens. |
| textual approach. In this approach you can see the | | | | Case-4: |
| XML file and you can easily understand the attributes | | | | In case of inheritance, your super class does not |
| of the object. Similarly to obtain the object graph from | | | | implement Serializable interface but your sub class |
| the XML file, you can use XMLDecoder. All these | | | | does. |
| classes have been defined in the java.beans package. | | | | Seriliazation will happen but with a lemon falvour. Here |
| Let me clarify all the aspects by citing the complete | | | | no exception will be thrown but your super class data |
| example. | | | | members or object properties of your super class will |
| Create a normal java bean or class having the | | | | be not be persisted. When you deserialize object, you |
| following structure. | | | | will get the default values of your super class object. |
| Let us see the class called Emp.java which is a normal | | | | Case-5: |
| java bean. | | | | This is the best case. You super class and sub class |
| There is another test harness class called | | | | implement serializable interface. |
| TestPersistence.java which exposes the use of | | | | Everything is fine here, serilization happens. |
| XMLEncoder and XMLDecoder. | | | | Case-6: |
| The following is the Emp.java.package | | | | If your object uses transient modifiers inside the |
| com.core.persist; | | | | objects, |
| /** | | | | You have to remember that transient objects or |
| * This is a simple java bean. | | | | variables will not be persisted in case of serialization. |
| * @author Debadatta Mishra(PIKU) | | | | Case-7: |
| * | | | | If your object uses volatile modifiers inside the object, |
| */public class Emp | | | | There is nothing to worry about, serialization will |
| {private String name = null;private int age = 0;private | | | | happen normally and data will be persisted. |
| String empId = null;public Emp() | | | | Case-8: |
| {super(); | | | | If your object uses static modifiers inside the object, |
| }public String getName() {return name; | | | | You have to remember that,since static is not a part |
| }public void setName(String name) {this.name = name; | | | | of object, so static variables or static object reference |
| }public int getAge() {return age; | | | | will not be persisted in case of seriaization. |
| }public void setAge(int age) {this.age = age; | | | | Case-9: |
| }public String getEmpId() {return empId; | | | | It is a very special case I am going to focus on. You |
| }public void setEmpId(String empId) {this.empId = empId; | | | | may encounter the following situations at the time of |
| } | | | | serialization. |
| } | | | | • You are not sure whether your super class does |
| The following is the TestPersistence.javapackage | | | | implement serializable interface. |
| com.core.persist;import java.beans.XMLDecoder;import | | | | • You do not have access to the source code of |
| java.beans.XMLEncoder;import | | | | your super class. |
| java.io.BufferedInputStream;import | | | | • Your super class may be a final class. |
| java.io.BufferedOutputStream;import | | | | • Your super class may contain noe-serializable |
| java.io.FileInputStream;import java.io.FileOutputStream; | | | | object reference. |
| /** | | | | In this case, if you feel frustration and disappointment, |
| * This is a test harness class to display the | | | | you can go for XMLEncoder and XMLDecoder as I |
| * use of XMLEncoder and XMLDecoder. | | | | have already explained. |
| * @author Debadatta Mishra(PIKU) | | | | If you want to persist the object using java’s |
| * | | | | serialization concept and mechanism, you have to do it |
| */public class TestPersistence | | | | little bit intelligently and manually. |
| {public static void main(String[] args) | | | | Please refer to the following piece of code. |
| { | | | | The following class name is Emp.javapackage |
| Emp emp = new | | | | com.core.persist;import java.io.ObjectInputStream;import |
| Id("A123");try | | | | java.io.ObjectOutputStream;import java.io.Serializable; |
| { | | | | /** |
| /* | | | | * This is a simple java bean. |
| * The following codes are used to persist the Emp | | | | * @author Debadatta Mishra(PIKU) |
| object graph | | | | * |
| */ | | | | */public class Emp implements Serializable |
| XMLEncoder encoder = new XMLEncoder(new | | | | {private static final long serialVersionUID = |
| BufferedOutputStream(new FileOutputStream("C: | | | | -164971138528601769L;private String name = null;private |
| oder.close(); | | | | int age = 0;private String empId = null;private transient |
| /* | | | | Project proj = null;public Emp() |
| * The following codes are used to obtain the Emp | | | | {super();proj = new Project(); |
| object graph | | | | }public String getName() {return name; |
| * from the XML document | | | | }public void setName(String name) {this.name = name; |
| */ | | | | }public int getAge() {return age; |
| XMLDecoder decoder = new XMLDecoder(new | | | | }public void setAge(int age) {this.age = age; |
| BufferedInputStream(new FileInputStream("C: | | | | }public String getEmpId() {return empId; |
| emp.xml"))); | | | | }public void setEmpId(String empId) {this.empId = empId; |
| Emp emp1 = ( Emp | | | | }public Project getProj() {return proj; |
| )decoder.readObject();decoder.close(); | | | | }public void setProj(Project proj) {this.proj = proj; |
| System.out.println("Emp Name=>"+emp1.getName()); | | | | } |
| System.out.println("Emp Age=>"+emp1.getAge()); | | | | /**You are proividing a default callback method |
| System.out.println("Emp Id=>"+emp1.getEmpId()); | | | | * for manual seriallization process. |
| }catch( Exception e ) | | | | * @param os of type {@link ObjectOutputStream} |
| {e.printStackTrace(); | | | | * @throws Exception of type {@link Exception} |
| } | | | | */private void writeObject( ObjectOutputStream os ) |
| } | | | | throws Exception |
| } | | | | {try |
| The following is the output of the above example. | | | | {os.defaultWriteObject();os.writeInt( |
| If you run the above classes, an XML document called | | | | proj.getProjectId());os.writeObject( |
| emp.xml will be created in the specified location. The | | | | proj.getPojectName() ); |
| xml document will look like the following. | | | | }catch( Exception e ) |
| 23 | | | | {e.printStackTrace(); |
| A123 | | | | } |
| John | | | | } |
| So you have stored the state of the Emp object in the | | | | /**You are providing default desrialization with |
| xml document. It is also required to load the Emp | | | | * some manual twik. |
| object from the xml document. For this purpose you | | | | * @param oin of type {@link ObjectInputStream} |
| have use XMLDecoder which has been used in the | | | | * @throws Exception of type {@link Exception} |
| test harness class. If you want to test the above two | | | | */private void readObject( ObjectInputStream oin ) |
| classes, you can copy the classes and change the | | | | throws Exception |
| package structure and you can run it. In case of | | | | {try |
| loading the object using XMLDecoder, it takes help | | | | {oin.defaultReadObject();proj = new |
| from java’s reflection system. | | | | e( (String) oin.readObject() ); |
| Advantages of XMLEncoder and XMLDecoder | | | | }catch( Exception e ) |
| • Since it is a textual representation of the object | | | | {e.printStackTrace(); |
| graph, anybody can see the XML file and it helps in the | | | | } |
| portability to any other system. | | | | } |
| • If you want to change the value of a particular | | | | } |
| property of an object, you can do it directly in the XML | | | | The following class name is Project.javapackage |
| document so that while using XMLDecoder, you will | | | | com.core.persist; |
| get your modified value. | | | | /** |
| • If the object’s variables are declared transient, | | | | * @author Debadatta Mishra(PIKU) |
| still you are able to store the complete object graph | | | | * |
| along with the transient variable’s value. This case | | | | */public class Project |
| is not possible in case of java object serialization. | | | | {private int projectId = 0;private String pojectName = |
| • It is also very easy and convenient in case of | | | | null;public Project() |
| object inheritance. There is no need to bother about | | | | {super(); |
| the super class and sub class. Some of the limitations | | | | }public String getPojectName() {return pojectName; |
| of normal java object serialization can be over come | | | | }public void setPojectName(String pojectName) |
| in this approach. | | | | {this.pojectName = pojectName; |
| Persistence using Serialization | | | | }public int getProjectId() {return projectId; |
| Serialization is a java’s default mechanism to save | | | | }public void setProjectId(int projectId) {this.projectId = |
| the state of the object or simply the object graph in | | | | projectId; |
| the file system. In this case your object will be | | | | } |
| persisted in the file system where the file is not human | | | | } |
| readable. It means that you are going to store the | | | | The following class name is TestSerialization.java |
| binary representation of the object graph in the file | | | | which is test harness class.package |
| system. This object serialization can be achieved using | | | | com.core.persist;import java.io.FileInputStream;import |
| the writeObject() method of the class | | | | java.io.FileOutputStream;import |
| ObjectOutputStream. The main thing you have to | | | | java.io.ObjectInputStream;import |
| remember is that the object you are going to persist | | | | java.io.ObjectOutputStream; |
| must implement Serialization interface which is called | | | | /** |
| as marker interface. In next article I will explain you the | | | | * @author Debadatta Mishra(PIKU) |
| use and the beauty of the marker interfaces. Similarly | | | | * |
| deserialization means retrieval of object from the | | | | */public class TestSerialization |
| saved state. You can achieve the deserialization using | | | | {public static void main(String[] args) |
| readObject() method of the ObjectInputStream class. | | | | { |
| Please refer below the following piece of code to | | | | Emp emp = new |
| achive serialization. | | | | ("John"); |
| The following is class called Emp. It implements | | | | Project proj = new |
| Serializable interface. There is another class called | | | | Z");emp.setProj(proj);try |
| TestSerialization. This class performs both serilization | | | | { |
| and deserilization. This is the normal way of serilization | | | | ObjectOutputStream ous = new |
| concept from java.package com.core.persist;import | | | | ObjectOutputStream(new FileOutputStream("D: |
| java.io.Serializable; | | | | test.ser"));ous.writeObject(emp);ous.close(); |
| /** | | | | ObjectInputStream oin = new ObjectInputStream(new |
| * This is a simple java bean. | | | | FileInputStream( |
| * @author Debadatta Mishra(PIKU) | | | | "D:/test.ser")); |
| * | | | | Emp emp1 = ( Emp )oin.readObject(); |
| */public class Emp implements Serializable | | | | System.out.println("Emp age----"+emp1.getAge()); |
| {private static final long serialVersionUID = | | | | Project proj1 = emp1.getProj(); |
| -164971138528601769L;private String name = null;private | | | | System.out.println("Proj Id-----"+proj1.getProjectId()); |
| int age = 0;public Emp() | | | | System.out.println("Proj |
| {super(); | | | | Name----"+proj1.getPojectName()); |
| }public String getName() {return name; | | | | }catch( Exception e ) |
| }public void setName(String name) {this.name = name; | | | | {e.printStackTrace(); |
| }public int getAge() {return age; | | | | } |
| }public void setAge(int age) {this.age = age; | | | | } |
| } | | | | } |
| } | | | | Please see the two methods writeObject() and |
| Class TestSerialization.javapackage | | | | readObject() inside the class Emp. These two |
| com.core.persist;import java.io.FileInputStream;import | | | | methods are significant in the sense that you are going |
| java.io.FileOutputStream;import | | | | to achieve serialization with your default object as well |
| java.io.ObjectInputStream;import | | | | as manual serialization with the non serializable object |
| java.io.ObjectOutputStream;public class | | | | with some data. When you call the methods |
| TestSerialization | | | | writeObject() and readObject() for a particular object |
| {public static void main(String[] args) | | | | these methods will be invoked automatically and will |
| { | | | | persist some default data. In these particular methods |
| Emp emp = new | | | | you are persisting data manually and thereby making |
| Emp();emp.setAge(23);emp.setName("John");try | | | | the whole object serializable. |
| { | | | | Conclusion |
| /* | | | | I hope that you will enjoy my article. If you find any |
| * Code to serialize or persist the object | | | | problems or errors, please feel free to send me a mail |
| */ | | | | in the address . This article is only meant for those |
| ObjectOutputStream ous = new ObjectOutputStream( | | | | who are new to java development. This article does |
| new FileOutputStream("D: | | | | not bear any commercial significance. Please provide |
| test.ser"));ous.writeObject(emp);ous.close(); | | | | me the feedback about this article. |