Java basics - serialization

1. Overview

We know that when two processes communicate remotely, they can send various data to each other, including text, pictures, audio and video, etc., and these contents are transmitted between networks in the form of binary sequences. So what do we need to do if we want to transfer objects between networks? Of course this is the serialization and deserialization we mentioned below.

For the sender, the object needs to be converted into a byte sequence and then transmitted on the network, and for the receiver, the byte sequence received from the network is converted into an object.

So what are the benefits of serialization?

(1) Using serialization can realize the permanent preservation of objects, that is, save them to local documents or databases.

(2) Using serialization can realize the transfer of objects between processes.

(3) The use of serialization can be brought to the purpose of passing objects between networks.

2. Definition

Serialization: The process of converting java objects into byte sequences, mainly to facilitate the preservation and reconstruction of object state.

Deserialization: The process of converting a sequence of bytes into a java object.

One thing to note here is that when serializing an object, not only the class information of the object but also the superclass information should be saved.

3. How Java implements serialization and deserialization

1. Serialization and deserialization API in JDK class library

(1) 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 resulting byte sequence to a target output stream;

(2) java.io.ObjectInputStream: represents the object input stream;

Its readObject() method reads byte sequences from the input stream, deserializes them into an object, and returns it;

2. Implement serialization requirements

Only objects of classes that implement the Serializable or Externalizable interface can be serialized, otherwise an exception is thrown!

3. How to implement Java object serialization and deserialization

Assuming a User class, its objects need to be serialized, there are three methods as follows:

(1) If the User class only implements the Serializable interface, it can be serialized and deserialized as follows

ObjectOutputStream uses the default serialization method to serialize the non-transient instance variables of the User object. 
ObjcetInputStream uses the default deserialization method to deserialize the non-transient instance variables of the User object.

(2) If the User class only implements the Serializable interface, and also defines readObject (ObjectInputStream in) and writeObject (ObjectOutputSteam out), serialization and deserialization are performed in the following ways.

ObjectOutputStream calls the writeObject(ObjectOutputStream out) method of the User object for serialization. 
ObjectInputStream will call the readObject(ObjectInputStream in) method of the User object to deserialize.

(3) If the User class implements the Externalnalizable interface, and the User class must implement the readExternal(ObjectInput in) and writeExternal(ObjectOutput out) methods, serialize and deserialize as follows.

ObjectOutputStream calls the writeExternal(ObjectOutput out)) method of the User object for serialization. 
ObjectInputStream will call the readExternal(ObjectInput in) method of the User object to deserialize.

4. Examples of serialization and deserialization

To better understand Java serialization and deserialization, a simple example is as follows:

package com.liutao.serializable;

import com.liutao.IO.Person;

import java.io. *;

/**
 * @Author:LIUTAO
 * @Description:
 * @Date:Created in 17:18 2018/4/22
 * @Modified By:
 */
public class JDKDemo {
    static String file = "D:\\IdeaProjects\\serialable.txt";
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Person person = new Person("liu","tao");
        // serialize the object
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(person);

        //Deserialize the byte stream
        FileInputStream fileInputStream = new FileInputStream(file);
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        Person person1 = (Person) objectInputStream.readObject();
        System.out.println(person1);
    }
}

We open the serial.txt file to see the byte sequence of the person object:


Similar to the .class file after our Java code is compiled, each character represents a certain meaning. The process of serialization and deserialization is the process of generating and parsing the above characters!

Serialization diagram:


Deserialization diagram:


Fourth, matters needing attention

1. When serializing, only the state of the object is saved, regardless of the method of the object;

2. When a parent class implements serialization, the subclass automatically implements serialization, and there is no need to explicitly implement the Serializable interface;

3. When an instance variable of an object refers to other objects, the reference object is also serialized when the object is serialized;

4. Not all objects can be serialized. As for why not, there are many reasons, such as:

  • For security reasons, for example, an object has fields such as private and public. For an object to be transmitted, such as writing to a file, or performing RMI transmission, etc., in the process of serialization and transmission, the private and other fields of this object are unprotected;

  • For resource allocation reasons, such as socket and thread classes, if they can be serialized, transmitted or saved, they cannot be re-allocated, and there is no need to do so;

5. Member data declared as static and transient types cannot be serialized. Because static represents the state of the class, transient represents the temporary data of the object.

6. The serialization runtime associates each serializable class with a version number called serialVersionUID, which is used during deserialization to verify that the sender and receiver of the serialized object are loaded for that object Classes compatible with serialization. Give it an explicit value. Explicitly defining serialVersionUID serves two purposes:

  • In some cases, different versions of a class are expected to be compatible with serialization, so it is necessary to ensure that different versions of a class have the same serialVersionUID;

  • In some cases, you do not want different versions of a class to be serializable, so you need to ensure that different versions of a class have different serialVersionUIDs.

7. There are many basic classes in Java that have implemented the serializable interface, such as String, Vector, etc. But for example HashTable does not implement the serializable interface;

8. If the member variable of an object is an object, then the data members of this object will also be saved! This is an important reason why serialization can be used to solve deep copy;

V. Summary

At present, when we serialize, we can not only use the serialization tools provided by JDK, but also use Hessian and ProtoBuff for serialization.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324653965&siteId=291194637