The practice of serialization and deserialization of Java objects

Source: Internet
Author: User
Tags object serialization

When two processes are communicating remotely, each other can send various types of data. Regardless of the type of data, it is transmitted over the network in the form of a binary sequence. The sender needs to convert the Java object to a sequence of bytes to be transmitted over the network, and the receiver needs to revert the byte sequence back to the Java object.

The process of converting a Java object to a sequence of bytes is called serialization of an object.

The process of reverting a sequence of bytes to a Java object is called deserialization of the object.

There are two main uses for serialization of objects:

1) The object's byte sequence is permanently saved to the hard disk, usually stored in a file;

2) A sequence of bytes that transmits an object over the network.

  A Serialization APIs in the JDK class library

Java.io.ObjectOutputStream represents an object output stream, and its writeobject (object obj) method serializes the Obj object specified by the parameter and writes the resulting sequence of bytes to a target output stream.

Java.io.ObjectInputStream represents an object input stream, and its readobject () method reads a sequence of bytes from a source input stream, deserializes them into an object, and returns them.

Only objects of classes that implement the serializable and Externalizable interfaces can be serialized. The Externalizable interface inherits from the serializable interface, and the class that implements the Externalizable interface controls the serialization behavior entirely by itself, whereas classes that implement the serializable interface can take the default serialization method.

Object serialization consists of the following steps:

1) Create an object output stream, which can wrap a different type of target output stream, such as a file output stream;

2) writes an object through the WriteObject () method of the object output stream.

The steps for deserializing an object are as follows:

1) Create an object input stream, which can wrap a different type of source input stream, such as a file input stream;

2) The object is read through the ReadObject () method of the object input stream.

Let us take a look at a corresponding example, the contents of the class are as follows:

 Import Java.io.*;import Java.util.date;public class Objectsaver {

public static void Main (string[] args) Throws Exception {ObjectOutputStream out = new ObjectOutputStream (New FileOutputStream ("D:" "objectfile.obj"));
 Serialized Object Customer customer = new Customer ("pistachio", 24); Out.writeobject ("Hello!"); Out.writeobject (New Date ()); Out.writeobject (customer);  Out.writeint (123); Out.close (); 
//Deserialize the object ObjectInputStream in = new ObjectInputStream (New FileInputStream ("D:" "objectfile.obj")); System.out.println ("obj1=" + (String) in.readobject ()); System.out.println ("obj2=" + (Date) in.readobject ()); Customer OBJ3 = (customer) in.readobject (); System.out.println ("obj3=" + obj3); int obj4 = In.readint (); System.out.println ("obj4=" + obj4); In.close ();}} Class Customer implements Serializable {private String name;private int age;public Customer (String name, int age) {This.na me = Name;this.age = age;} Public String toString () {return ' name= ' + name + ", age=" + Age;}}

The output results are as follows:


  Two Implementing the Serializable interface

ObjectOutputStream can only serialize objects of classes that are serializable interfaces. By default, ObjectOutputStream is serialized by default, which serializes only the object's non-transient instance variables, not the instance variables of the object's transient, and does not serialize static variables.

When ObjectOutputStream is deserialized in the default way, it has the following characteristics:

1) If the class to which the object belongs in memory has not been loaded, the class is loaded and initialized first. If the corresponding class file does not exist in the classpath, then ClassNotFoundException will be thrown;

2) does not invoke any of the constructor methods of the class when deserializing.

If the user wants to control how the class is serialized, the WriteObject () and ReadObject () methods in the following form can be provided in the Serializable class.

private void WriteObject (Java.io.ObjectOutputStream out) throws Ioexceptionprivate void ReadObject ( Java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

When ObjectOutputStream serializes a customer object, this method is executed if the object has the WriteObject () method, otherwise it is serialized by default. In the WRITEOBJECTT () method of the object, you can call the ObjectOutputStream Defaultwriteobject () method first so that the object output stream performs the default serialization operation first. The same can be said of deserialization, but this time it is the Defaultreadobject () method.

Some objects contain sensitive information that should not be disclosed externally. If they are serialized by default, their serialized data may be stolen by criminals when they are transmitted over the network. For this type of information, they can be encrypted and then serialized, the deserialization is required to decrypt, and then revert to the original information.

The default serialization method serializes the entire object graph, which requires recursive traversal of the object graph. If the object graph is complex, the recursive traversal operation consumes a lot of space and time, and its internal data structure is a bidirectional list.

When applied, if you change some member variables to the transient type, you save space and time and improve the performance of serialization.

  Three Implementing the Externalizable Interface

The Externalizable interface inherits from the serializable interface, and if a class implements the Externalizable interface, it will be entirely controlled by this class for its own serialization behavior. The Externalizable interface declares two methods:

public void Writeexternal (ObjectOutput out) throws Ioexceptionpublic void Readexternal (ObjectInput in) throws IOException, ClassNotFoundException

The former is responsible for the serialization operation, which is responsible for deserializing the operation.

When an object of a class that implements the Externalizable interface is deserialized, the class's constructor with no arguments is called first, which is different from the default deserialization method. A Java.io.InvalidException:no valid constructor exception is thrown if the class's constructor with no parameters is removed, or the access permission for the constructor is set to private, default, or protected level.

  Four Serialization compatibility for different versions of serializable classes

Any class that implements the Serializable interface has a static variable that represents the serialized version identifier:

Private static final long serialversionuid;

The value of the above serialversionuid is generated automatically by the Java Runtime Environment based on the internal details of the class. If the source code of the class is modified and then recompiled, the value of the serialversionuid of the newly generated class file may also change.

The default value of the Serialversionuid class is entirely dependent on the implementation of the Java compiler, and compiling with different Java compilers for the same class may lead to different serialversionuid and possibly the same. To improve the independence and certainty of serialversionuid, it is strongly recommended that the definition serialversionuid be displayed in a serializable class, giving it a definite value. There are two ways to explicitly define SERIALVERSIONUID:

1) In some cases, you want the different versions of the class to be serializable compatible, so you need to ensure that the different versions of the class have the same serialversionuid;

The practice of serialization and deserialization of Java objects

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.