Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

Introduction: Serializable is often seen in JAVA programs and in some reference types provided by the JDK.

Role of serialization

When we define the Serializable interface in our daily development, we usually implement the Serializable interface. When we click to view the Serializable interface, we find that it is just an interface without any methods. So what does this interface do? Here is a knowledge point THAT I want to share today is serialization (in the interview, I will often be asked: what is serialization?). I found that my understanding of this knowledge point was always vague at the beginning, but NOW I have some understanding. Serialization: Write a Java object to a hard disk or transfer it to another computer on the network. In this case, we need to convert the corresponding object into a byte stream through Java. Serialization is the process of converting the state information of an object into a form that can be stored or transmitted. During serialization, an object writes its current state to a temporary or persistent store. Later, the object can be recreated by reading or deserializing its state from the store (in my own understanding: Serialization is all about proper and complete transfer of Java objects. Our data, if it goes from one computer to another, is eventually transferred in binary bits. One byte is equal to 8 bits.)

Serializable

When defining an entity class, you can often see that we implement a Serializable interface code as follows, to ensure that the SerialVersionId value is implemented consistently across Java compilers. Our serializable class must have an obvious SerialVersionId value and strongly declare that it needs to be modified with private. It does not have any implementation in the Serializable interface, which is used for instantiation.

Serializable can also be clearly seen in some reference types. Here I take Integer as an example. We can see all the inheritance and implementation of Integer as shown in the figure below. If a class implements a serialization interface, that interface is a signature interface, and the annotation class can be sequenced

After realizing the serialization interface, if the serialVersionUID value is not declared, the system will generate one by default. You can also declare a serialVersionUID value by yourself, and its initial value can be assigned in two ways. One is to set 1L or use JDK tools to set a value randomly.

public class UserInfo implements Serializable {
    private static final long serialVersionUID = 1L;
}
Copy the code

Today’s analysis of serialization content is only we are generally easy to understand, but on the deeper things still need to learn more: such as the implementation of serialization will bring what overhead to the program? The problems such as