Why do we need serialization and deserialization in Java; and what is it exactly? Show
Let’s understand this by examining computer games. When we stop or pause a running computer game, it usually starts from the state where it was left off when we play it again. This is possible through the process of Serialization; which is saving the current object state as byte stream into file or database. Then to restore the object’s state when we access the game again is called Deserialization. Before we dive deeper into it, let’s first understand what streams are in computer systems. A stream is nothing but the sequence of data elements. In a computer system, there is a source that generates data in the form of stream and there is a destination which reads and consumes this stream. Here are the types of streams:
Eventually, we can use this byte stream to retrieve the stored values and restore the object’s old state. This process of restoring the object’s old state is known as Deserialization. Similar to a multi-tier JAVA/J2EE application (client-server RMI applications), when we make a remote invocation method or RMI from a web tier to app tier, we need to send the data value object that transfers the required business information from web tier to app tier after Serialization (we implement java.io. Serializable (Marker Interface) that we are now going to discuss in detail ). Marker InterfaceMarker Interfaces in JAVA are interfaces which do not have any field and method. They are just used to inform the JVM that the class is implementing these interfaces that have special meaning or behavior. Following are the well-known Marker Interfaces.
Note: All Marker interfaces— except serializable interface—are replaced by annotations since JAVA 5. Data and Object stream InterfacesThe following are the data and object stream interfaces which every Object Stream class implements. Object Stream class implements either of the two interfaces.
Note: All the primitive data I/O methods which are already covered in Data Streams are also implemented in object streams because these interfaces are the sub interface of Data streams interfaces. Object Streams ClassesThe following are the two classes used for Object Streams.
Transient KeywordIn an object, we may not want to save sensitive information such as keys, Password, etc.; so we protect that field from being saved during the process of serialization. Placing the transient keyword before any field of a class object makes sure that the value of such fields won‘t be stored as a part of serialization. And when we deserialize, the value of these transient fields will have the default value (null for a JAVA String primitives). We will understand the complete theory of serialization and deserialization that we just discussed with the help of the following JAVA example. DataValueObject.javapackage com.java; import java.io.Serializable; public class DataValueObject implements Serializable{ private static final long serialVersionUID = 1L; private String customer; private String business; transient private String contractID; transient private String passKeys; public String getCustomer() { return customer; } public void setCustomer(String customer) { this.customer = customer; } public String getBusiness() { return business; } public void setBusiness(String business) { this.business = business; } public String getContractID() { return contractID; } public void setContractID(String contractID) { this.contractID = contractID; } public String getPassKeys() { return passKeys; } public void setPassKeys(String passKeys) { this.passKeys = passKeys; } @Override public String toString() { String value = "customer : " + customer + "\nbusiness : " + business + "\ncontractID : " + contractID + "\npassKeys : " + passKeys; return value; } }Explanation
SerializationDemo.javapackage com.java; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SerializationDemo { /** * This method is used to read data from file for deSerialization. * * @param file * @return * @throws IOException * @throws ClassNotFoundException */ public static Object deSerialization(String file) throws IOException, ClassNotFoundException { FileInputStream fileInputStream = new FileInputStream(file); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); ObjectInputStream objectInputStream = new ObjectInputStream(bufferedInputStream); Object object = objectInputStream.readObject(); objectInputStream.close(); return object; } /** * This method is used to write data to file for Serialization. * * @param file * @param object * @throws IOException */ public static void serialization(String file, Object object) throws IOException { FileOutputStream fileOutputStream = new FileOutputStream(file); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); ObjectOutputStream objectOutputStream = new ObjectOutputStream(bufferedOutputStream); objectOutputStream.writeObject(object); objectOutputStream.close(); } }Explanation
SerializationImplementation.javapackage com.java; import java.io.IOException; public class SerializationImplementation { public static void main(String args[]) { DataValueObject dataValueObject = new DataValueObject(); dataValueObject.setCustomer("Debbie"); dataValueObject.setBusiness("JAVA Concepts"); dataValueObject.setContractID("ZZZZZZ"); dataValueObject.setPassKeys("!@wer#$"); try { SerializationDemo.serialization("fileToSave.txt", dataValueObject); DataValueObject object = (DataValueObject) SerializationDemo.deSerialization("fileToSave.txt"); System.out.println(object.toString()); } catch (IOException exp) { exp.printStackTrace(); } catch (ClassNotFoundException exp) { exp.printStackTrace(); } } }ExplanationIn this class, we are testing our serialization and deserialization procedure in the following four steps. First, we are populating all four fields of the data value object. Second, we are calling serialization method after passing the file path and name as the first parameter fileToSave.txt; and data value object as the second parameter. This method will write the state of data value object to the byte stream into the file fileToSave.txt. Third, we are calling deserialization method after passing the file path and name as the first parameter fileToSave.txt. This will read the stored object’s state and return the deserialized object which is down casted to the data value object class. Lastly, we are printing the toString () method of the data value object class which was overridden. fileToSave.txt FILE content after serialization as byte stream InferenceAs printed on the console below, we can observe that our serialization and deserialization methods in JAVA program were able to serialize and deserialize the data value object, respectively. We can observe that the values of the fields contractID and passKeys are null (default string value) and were declared as transient, and therefore, were not stored in the file while saving the objects’ state into the byte stream. And that wrap’s up this tutorial. With Java as one of the most used languages in the world, there’s always more to learn about Java. And if you’re a beginner, just keep coding! Author’s BioAparajita Jain is a senior Java developer and a technical writer with more than 6 years of experience. She has expertise in Java, PHP, and Python. She loves teaching and sharing knowledge through technical writing. Currently working full time as Java developer in one of the leading banks in Canada. How do you serialize an object in a program?Serializing an Object. When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing. Note − When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.
How to do Java custom serialization using readobject and WriteObject? Java custom serialization using readObject and writeObject 1 Java Custom Serialization#N#In most of cases, when you will customize java serialization, you will be writing the... 2 Override default serialization to add validation#N#Sometimes you may have requirement where you only want to perform... 3 Summary More ...
What is serialization in Java?Java - Serialization. Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object. After a serialized object has been written into a file, it can be read from the file and ...
How do you test if a class is serializable?The test is simple: If the class implements java.io.Serializable, then it is serializable; otherwise, it's not. The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file.
How do I serialize an object to a file?In short, in order to write an object to a file one should follow these steps:. Create a class that implements the Serializable interface.. Open or create a new file using FileOutputStream .. Create an ObjectOutputStream giving the above FileOutputStream as an argument to the constructor.. Use ObjectOutputStream.. Which method is used for object serialization?The ObjectOutputStream class contains writeObject() method for serializing an Object. The ObjectInputStream class contains readObject() method for deserializing an object.
Which class is used to write an object into the file?ObjectOutputStream . In order to enable writing of objects into a file using ObjectOutputStream , it is mandatory that the concerned class implements Serializable interface as shown in the class definition below. Reading objects in Java are similar to writing object using ObjectOutputStreamObjectInputStream .
What are the requirements for a class that you want to serialize with ObjectOutputStream?Classes that are eligible for serialization need to implement a special marker interface, Serializable. Both ObjectInputStream and ObjectOutputStream are high level classes that extend java. io. InputStream and java.
|