Object serialization and deserialization

Source: Internet
Author: User

When two processes perform remote communication, they can send different types of data to each other. Regardless of the type of data, it is transmitted on the network in the form of binary sequence. The sender needs to convert the Java object into a byte sequence before it can be transmitted over the network. The receiver needs to restore the byte sequence to a Java object.

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

The process of restoring a byte sequence to a Java object is called object deserialization.

Object serialization has two main purposes:

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

2) transmits the object's byte sequence over the network.

I. serialization API in JDK class library

Java. Io. objectoutputstream represents the object output stream. Its writeobject (Object OBJ) method can serialize the OBJ object specified by the parameter and write the obtained byte sequence to a target output stream.

Java. Io. objectinputstream indicates the object input stream. Its readobject () method reads byte sequences from a source input stream, deserializes them into an object, and returns it. ,

Only objects of classes that implement the serializable and externalizable interfaces can be serialized. The externalizable interface inherits from the serializable interface. classes that implement the externalizable interface completely control the serialization behavior. classes that only implement the serializable interface can adopt the default serialization method.

Object serialization includes the following steps:

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

2) write an object using the writeobject () method of the object output stream.

The steps for object deserialization are as follows:

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

2) read the object through the readobject () method of the object input stream.

Let's look at a corresponding example. The class content is 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 "));

// Serialize the object

Customer customer = new customer ("A honey fruit", 24 );

Out. writeobject ("Hello! ");

Out. writeobject (new date ());

Out. writeobject (customer );

Out. writeint (123); // write basic data

Out. Close ();

// Deserialization 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. Name = Name;

This. Age = age;

}

Public String tostring (){

Return "name =" + name + ", age =" + age;

}

}

The output result is as follows:

Obj1 = hello!

Obj2 = SAT Sep 15 22:02:21 CST 2007

Obj3 = Name = honey fruit, age = 24

Obj4= 123

Therefore, the example is simple and will not be detailed here.

Ii. Implement the serializable Interface

Objectoutputstream can only serialize the class objects of the serializable interface. By default, objectoutputstream is serialized by default. This serialization method only serializes non-transient instance variables of the object, instead of the transient instance variables of the object, static variables are not serialized.

When objectoutputstream is deserialized by default, it has the following features:

1) if the class to which the object belongs in the memory is not loaded, the class will be loaded and initialized first. If no corresponding class file exists in classpath, classnotfoundexception is thrown;

2) during deserialization, no constructor of the class is called.

If you want to control the serialization method of the class, you can provide the following writeobject () and readobject () methods in the serializable class.

Private void writeobject (Java. Io. objectoutputstream out) throws ioexception

Private void readobject (Java. Io. objectinputstream in) throws ioexception, classnotfoundexception;

When objectoutputstream serializes a customer object, if the object has a writeobject () method, this method is executed. Otherwise, the method is serialized by default. In the writeobjectt () method of the object, you can first call the defaultwriteobject () method of objectoutputstream so that the object output stream executes the default serialization operation first. Likewise, deserialization can be obtained, but this time it is the defaultreadobject () method.

Some objects contain sensitive information, which should not be made public. If they are serialized by default, their serialized data may be stolen by criminals during network upload or transmission. This type of information can be encrypted and then serialized. During deserialization, it needs to be decrypted before being restored to the original information.

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

In an application, if some member variables are changed to the transient type, it will save space and time and improve the serialization performance.

3. Implement the externalizable Interface

The externalizable interface inherits from the serializable interface. If a class implements the externalizable interface, this class controls its own serialization behavior completely. The externalizable interface declares two methods:

Public void writeexternal (objectoutput out) throws ioexception

Public void readexternal (objectinput in) throws ioexception, classnotfoundexception

The former is responsible for serialization, and the latter is responsible for deserialization.

When deserializing objects of classes that implement the externalizable interface, the class construction method without parameters is called first, which is different from the default deserialization method. If you delete a class constructor without parameters, or set the access permission of the constructor to private, default, or protected, Java is thrown. io. invalidexception: no valid constructor exception.

Iv. serialization compatibility of different versions of serializable classes

All classes that implement the serializable interface have a static variable that represents the serialized version identifier:

Private Static final long serialversionuid;

The above serialversionuid value is automatically generated in the Java Runtime Environment according to the internal details of the class. If the source code of the class is modified and re-compiled, the serialversionuid value of the newly generated class file may also change.

The default value of serialversionuid of the class is completely dependent on the implementation of the Java compiler. For the same class, compiling with different Java compilers may lead to different serialversionuid and may also be the same. To improve the independence and certainty of serialversionuid, we strongly recommend that you define serialversionuid in a serializable class and assign it a clear value. Serialversionuid can be explicitly defined for two purposes:

1) In some cases, different versions of the class are expected to be compatible with serialization. Therefore, ensure that different versions of the class have the same serialversionuid;

2) In some cases, different versions of the class are not required to be compatible with serialization. Therefore, make sure that different versions of the class have different serialversionuid.

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.