The login
registered
Write an article
Home page
Download the APP

Serialization and deserialization of Java objects

Ye maple _ the high

Serialization and deserialization of Java objects

Concepts of serialization and deserialization

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

The process of restoring a sequence of bytes to an object is called deserialization of an object.

Object serialization has two main uses:

1) To permanently store the byte sequence of an object on hard disk, usually in a file;

2) Transmit the byte sequence of the object over the network.

What scenarios involve the concepts of serialization and deserialization

In many applications, objects need to be serialized out of memory and onto physical hard disks for long-term storage. For example, the most common is the Session object in the Web server. When there are 100,000 users accessing it concurrently, there may be 100,000 Session objects, and the memory may not be enough. Therefore, the Web container will serialize some sessions to the hard disk first, and then restore the objects stored in the hard disk to the memory when they need to be used.

When two processes are communicating remotely, they can send various types of data to each other. Data of any type is sent over the network as binary sequences. The sender needs to convert this Java object into a sequence of bytes before it can be sent over the network; The receiver needs to restore the byte sequence back to Java objects.

For a real example, the Proxy pattern is introduced when we need to use objects that are complex or take a long time to construct. For example, if building an object takes time and computer resources, Proxy mode allows us to control the situation until we need to use the actual object. A Proxy usually contains the same methods as the object to be used, and once you start using the object, these methods are passed to the actual object through the Proxy.

Reading: In today’s microservitization, it is time-consuming to construct many complex objects. In order to save costs, some companies circle these complex objects and write that the service starts at the remote end B and provides access to the service in the form of Proxy at the calling end A. The process of remotely calling from B to A in between forms the operations related to Java object serialization and deserialization!

To highlight the power of Java serialization and deserialization, let’s take a look at remote proxies (proxy patterns), which are often mentioned in design patterns;

Iii. What is a remote Proxy?


Remote agent role

The JDK provides a Proxy class: import java.lang.reflect.proxy; Take a look at the Proxy implementation


Proxy implements the Serializable interface in the JDK, but how does Proxy implement the server-side object to run on the client? Here we need to explain a personal understanding process:

Step 1: The remote JVM (server) sends the byte sequence of the “object” locally (client) by serializing it and transferring it over the network.

Step 2: The local Proxy deserializes the received byte sequence into an “object” and makes this “object” live in the local JVM.

From the above two steps, serialization is done on the server side; Deserialization is done on the client side; So there is a problem, from the source, Proxy (local) implementation of deserialization, where the server implementation of serialization? With this in mind, I continued to look at all the server code and found that some companies directly Serialize entities, while others annotate @serializable classes using aspects, but eventually Serialize;

The serialization API in the JDK class library

Java. IO. ObjectOutputStream represents the output stream Object, its writeObject (Object obj) methods for parameter specifies the obj Object serialization, to get the sequence of bytes to a target output stream.

Java. IO. ObjectInputStream representative object input stream, its readObject () method from the source of a sequence of bytes read from the input stream, deserialize them as 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, while classes that implement only the Serializable interface can adopt the default serialization method.

Object serialization includes the following steps:

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

2) Write objects via the writeObject() method of the object output stream.

The steps for deserializing objects are as follows:

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

2) Read objects through the readObject() method of the object input stream.

Object serialization and antisequence examples

1) Define a Person class that implements the Serializable interface


2) Serialize and deserialize the Person class object




3) The code running results are as follows:


The role of serialVersionUID

SerialVersionUID: Literally the serialized version number. Classes that implement the Serializable interface have a static variable representing the serialized version identifier

private static final long serialVersionUID


The serialVersionUID generated by adding generated Serial Version ID is generated based on the class name, interface name, method, and attribute.

The real purpose of the serialized version ID: When attributes are added to the entity, the class in the file stream is incompatible with the class in the classpath, which is the modified class. For security reasons, the program throws an error and refuses to load. What if we really need to add a field or method after serialization? What should I do? Specify the serialVersionUID yourself. In this example, if the serialVersionUID of the Person class is not specified, the Java compiler automatically gives the class a summary algorithm, similar to the fingerprint algorithm. As long as the file has an extra space, the resulting UID will be completely different, ensuring that the number is unique among so many classes. So, after adding a field, since serialVersionUID is not explicitly specified, the compiler generates another UID for us, which of course is not the same as the one previously saved in the file, resulting in two different serialization versions. Therefore, as long as we specify the serialVersionUID ourselves, we can add a field or method after serialization without affecting the later restoration, and the restored object can still be used, but also more methods or properties can be used. It can be said that the serialVersionUID is the only token that serialization and deserialization know each other.

7. Value of serialVersionUID

The value of serialVersionUID is automatically generated 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 serialVersionUID in the newly generated class file may also change.

The default value of serialVersionUID for a class is completely dependent on the implementation of the Java compiler. For the same class, compiling with different Java compilers may result in different or identical serialVersionUID. To improve the independence and determinism of the serialVersionUID, it is strongly recommended that the definition serialVersionUID, shown in a serializable class, be given an explicit value.

Explicitly defining the serialVersionUID serves two purposes:

1. In some cases, you want different versions of a class to be compatible with serialization, so you need to ensure that different versions of a class have the same serialVersionUID;

2. In some cases, you do not want different versions of a class to be compatible with serialization, so you need to ensure that different versions of a class have different serialVersionUID.

Recommended readingMore highlights

  • … class = ‘class1’ > Chapter 1 Content introduction 20 Chapter 2 JavaSE basics 21 一… Zhenyang Wang read 77,420 comments 25 likes 510
  • The main use of object serialization is to ensure the integrity of an object when passing and saving it… When I read 4,151 comments 0 likes 21
  • Serialization and deserialization Concepts Serialization is the process of describing an object as a series of bytes; Deserialize de… Step by step read 445 comments 0 likes 10
  • Java Serializable serialization and deserialization concepts and serialVersion… … class = ‘class1’ > Java Serializable Serializable interface Hadoop_null Read 87 Comments 0 upvotes 0
  • IO streams (operating file contents): conversion streams, output/input character streams, object serialization, sequence streams, Prope… InputStreamReader is a bridge between the stream of bytes and the stream of characters. The struggling Lao Wang Read 1,612 comments 0 upvotes 37