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:

1 ImportJava.io.*;2 Importjava.util.Date;3 /**4 * Object serialization and deserialization test class.5 * @author<a href= "Mailto:[email protected]" >AmigoXie</a>6 * @version1.07 * Creation date:2007-9-15-PM 21:45:488 */9  Public classObjectsaver {Ten    /** One *@paramargs A *@author<a href= "Mailto:[email protected]" >AmigoXie</a> - * Creation date:2007-9-15-PM 21:45:37 -    */ the  Public Static voidMain (string[] args)throwsException { -ObjectOutputStream out =NewObjectOutputStream -(NewFileOutputStream ("D:" "Objectfile.obj")); -    //Serializing Objects +Customer customer =NewCustomer ("Pistachio", 24); -Out.writeobject ("Hello!"); +Out.writeobject (NewDate ()); A Out.writeobject (customer); atOut.writeint (123);//write basic type Data - out.close (); -    //deserializing Objects -ObjectInputStream in =NewObjectInputStream -(NewFileInputStream ("D:" "Objectfile.obj")); -System.out.println ("obj1=" +(String) in.readobject ()); inSystem.out.println ("obj2=" +(Date) in.readobject ()); -Customer obj3 =(Customer) in.readobject (); toSystem.out.println ("obj3=" +obj3); +    intObj4 =in.readint (); -System.out.println ("obj4=" +obj4); the in.close (); * } $ }Panax Notoginseng classCustomerImplementsSerializable { - PrivateString name; the Private intAge ; +  PublicCustomer (String name,intAge ) { A  This. Name =name; the  This. Age =Age ; + } -  PublicString toString () { $ return"Name=" + name + ", age=" +Age ; $ } -}

The output results are as follows:

1 obj1= Hello! 2 obj2=sat Sep 22:02:21 CST3 obj3=name= pistachio, age=244 obj4=123

The example is simple and is not detailed here.

Two. Implementing the Serializable interface

ObjectOutputStream can only serialize objects for classes of 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 by default, 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 is thrown, and

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.

1 Private void throws IOException 2 Private void 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 of the objects contain sensitive information that is not intended to be exposed 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 of

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. Implement the Externalizable interface

Externalizable interface inherits from the serializable interface, if a class implements the Externalizable interface, Then this class will control its own serialization behavior entirely. The Externalizable interface declares two methods:

1  Public void throws IOException 2  Public void 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:

1 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;

2) In some cases, you do not want different versions of the class to be serializable compatible, so you need to ensure that different versions of the class have different serialversionuid.

The practice of serialization and deserialization of Java objects

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.