A deep understanding of the application of serialization and deserialization of Java objects _java

Source: Internet
Author: User
Tags object serialization serialization

When two processes are communicating remotely, they can send different 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 into a byte sequence to be routed over the network, and the receiver needs to revert the byte sequence back to the Java object.
The process of converting Java objects into byte sequences is called serialization of objects.
The process of restoring a byte sequence to a Java object is called deserialization of an 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 transfer the byte sequence of the object on the network.
A Serialization APIs in the JDK class library
Java.io.ObjectOutputStream represents an object output stream whose WriteObject (object obj) method serializes the Obj object specified by the parameter and writes the resulting byte sequence to a target output stream.
Java.io.ObjectInputStream represents an object input stream whose 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, and the class that implements only the serializable interface can use the default serialization method.
Object serialization consists of the following steps:
1 Create an object output stream that can wrap a different type of target output stream, such as a file output stream;
2 The object is written through the WriteObject () method of the object output stream.
The steps to deserialize an object are as follows:
1 Create an object input stream that can wrap a different type of source input stream, such as a file input stream;
2 The object is read by the ReadObject () method of the object input stream.
Let's look at a corresponding example, the contents of the class are as follows:

Copy Code code 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"));

Serializing an Object
Customer customer = new Customer ("Honey Fruit", 24);
Out.writeobject ("Hello!");
Out.writeobject (New Date ());
Out.writeobject (customer);
Out.writeint (123);
Out.close ();

Deserializing objects
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 results are as follows:


two. Implement Serializable interface
ObjectOutputStream can only serialize objects on the serializable interface's classes. By default, ObjectOutputStream is serialized by default, which serializes only transient instance variables of an object without serializing the transient instance variable of the object, nor does it serialize the static variable.
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, the classnotfoundexception is 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, you can provide the following form of WriteObject () and ReadObject () methods in the Serializable class.
Copy Code code as follows:

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, or it is serialized by default. In the WRITEOBJECTT () method of the object, you can first invoke the ObjectOutputStream Defaultwriteobject () method so that the object output stream performs the default serialization operation. The same can be found in the case of deserialization, but this time it is the Defaultreadobject () method.

Some of the objects contain sensitive information that is not publicly available. If they are serialized by default, their serialized data is transmitted over the network and may be stolen by the lawless elements. For such information, they can be encrypted and then serialized, and decrypted when deserialized, and then restored to the original information.

The default serialization method serializes the entire object graph, which requires a 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 two-way list.
When applied, changing to a transient type for some member variables saves space and time and improves serialization performance.
Three Implement Externalizable interface
The Externalizable interface inherits from the serializable interface, and if a class implements the Externalizable interface, then it is entirely up to the class to control its own serialization behavior. The Externalizable interface declares two methods:
Copy Code code as follows:

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

the former is responsible for serialization operations, the latter is responsible for deserialization operations.
When deserializing an object of a class that implements the Externalizable interface, the constructor of the class without arguments is invoked first, as opposed to the default deserialization method. A Java.io.InvalidException:no valid constructor exception is thrown if the class's constructor is deleted without parameters, or if the access permission for the constructor is set to private, default, or protected levels.
Four. Serialization compatibility for different versions of a serializable class
All classes that implement the Serializable interface have a static variable that represents the serialized version identifier:
Copy Code code as follows:

Private static final long serialversionuid;

The above serialversionuid values are generated automatically by the Java Runtime Environment based on the internal details of the class. If you modify the source code for the class, and then recompile, the value of the serialversionuid of the newly generated class file may change.
The default value of a class's serialversionuid is entirely dependent on the implementation of the Java compiler, and for the same class, compiling with a different Java compiler may lead to different serialversionuid, and possibly the same. In order to improve the independence and certainty of serialversionuid, it is strongly recommended that the definition shown in a serializable class be serialversionuid, giving it a definite value. Explicit definition of Serialversionuid has two uses:
1 In some cases, you want different versions of the class to be compatible with serialization, so you need to ensure that different versions of the class have the same serialversionuid;
2 In some cases, you do not want different versions of the class to be compatible with serialization, so you need to ensure that different versions of the class have different serialversionuid

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.