Serialization and deserialization as a relatively basic knowledge of Java, we also have a few words to say, but I believe that many partners master is just a few words, if further research to ask Java how to achieve serialization and deserialization, you may be at a loss! What is serialization? What is deserialization? What is deserialization? What is deserialization? Then go home and wait for notice!
1. Basic Concepts
1. What is serialization and deserialization
(1) Java serialization refers to the process of converting Java objects into byte sequences, while Java deserialization refers to the process of restoring byte sequences to Java objects;
(2) ** serialization: The main use of ** object serialization is to ensure the integrity and transitivity of the object when passing and saving the object. Serialization is the process of converting an object into an ordered stream of bytes for transmission over the network or storage in a local file. The serialized byte stream holds the state of the Java object and its associated description. The core function of serialization mechanism is the preservation and reconstruction of object state.
(3) ** deserialization: after the ** client obtains the serialized object byte stream from the file or the network, it reconstructs the object through deserialization according to the object state and description information saved in the byte stream.
(4) In essence, serialization is to write the state of the entity object to the ordered byte stream in a certain format, and deserialization is to rebuild the object from the ordered byte stream and restore the state of the object.
2. Why serialization and deserialization
We know that when two processes communicate remotely, they can send each other various types of data, including text, pictures, audio, video, and so on, all of which are sent over the network in the form of binary sequences.
When two Java processes communicate, can object transfer be implemented between processes? The answer is yes! How do you do that? This requires Java serialization and deserialization!
In other words, on the one hand, the sender needs to convert this Java object into a sequence of bytes and send it over the network; On the other hand, the recipient needs to recover the Java object from the byte sequence.
Once we understand why we need Java serialization and deserialization, it’s natural to think about the benefits of Java serialization. The first is the persistence of data, which can be permanently stored on hard disk (usually in a file) through serialization, and the second is the remote communication through serialization, that is, the transmission of object byte sequences over the network.
In general, it can be summarized as follows:
(1) Permanently save the object, save the byte sequence of the object to a local file or database; (2) through serialization in the form of byte stream objects in the network for transmission and receipt; (3) Pass objects between processes through serialization;
3. Serialization algorithms generally do the following steps:
(1) Output the class metadata related to the object instance. (2) Recursively output the superclass description of the class until there are no more superclasses. (3) After the class metadata is finished, it starts to output the actual data value of the object instance from the topmost superclass. (4) Recursively output instance data from top to bottom
How does Java implement serialization and deserialization
Serialization and deserialization apis in JDK libraries
(1) Java. IO. ObjectOutputStream: it means the object output flow;
Its writeObject(Object OBj) method serializes the obJ Object specified by the parameter and writes the resulting byte sequence to a target output stream.
(2) Java. IO. ObjectInputStream: it means the object input stream;
Its readObject() method reads byte sequences from the source input stream, deserializes them into an object, and returns them;
2. Realize the serialization requirements
Only objects of classes that implement the Serializable or Externalizable interfaces can be serialized, otherwise an exception is thrown!
3, Java object serialization and deserialization method
Given a User class whose objects need to be serialized, there are three methods:
(1) If the User class only implements the Serializable interface, it can be serialized and deserialized as follows
ObjectOutputStream serializes the non-transient instance variables of the User object using the default serialization method. ObjcetInputStream uses the default deserialization method to deserialize non-transient instance variables of the User object.
(2) If the User class only implements Serializable interface and also defines readObject(ObjectInputStream in) and writeObject(ObjectOutputSteam Out), The following methods are used for serialization and deserialization.
ObjectOutputStream calls the writeObject(ObjectOutputStream out) method of the User object for serialization. ObjectInputStream will deserialize the User object by calling its readObject(ObjectInputStream in) method.
(3) If the User class implements Externalnalizable interface, and the User class must implement readExternal(ObjectInput in) and writeExternal(ObjectOutput Out) methods, Serialization and deserialization are performed as follows.
ObjectOutputStream calls the writeExternal(ObjectOutput Out) method of the User object for serialization. ObjectInputStream calls the User object’s readExternal(ObjectInput in) method for deserialization.
Step 4: Serialization in JDK libraries
Step 1: Create an object output stream that can wrap another type of target output stream, such as a file output stream:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\object.out"));
Copy the code
Step 2: Write objects using the writeObject() method of the object output stream:
oos.writeObject(new User("xuliugen"."123456"."male"));
Copy the code
Steps for deserialization in JDK libraries
Step 1: Create an object input stream that wraps another type of input stream, such as a file input stream:
ObjectInputStream ois= new ObjectInputStream(new FileInputStream("object.out"));
Copy the code
Step 2: Read the object through the readObject() method of the object output stream:
User user = (User) ois.readObject();
Copy the code
Note: In order to read data correctly and complete deserialization, you must ensure that objects are written to the output stream in the same order as objects are read from the input stream.
Examples of serialization and deserialization
To better understand Java serialization and deserialization, a simple example is as follows:
public class SerialDemo { public static void main(String[] args) throws IOException, Fos = new FileOutputStream(ClassNotFoundException {"object.out");
ObjectOutputStream oos = new ObjectOutputStream(fos);
User user1 = new User("xuliugen"."123456"."male"); oos.writeObject(user1); oos.flush(); oos.close(); Fis = new FileInputStream("object.out");
ObjectInputStream ois = new ObjectInputStream(fis);
User user2 = (User) ois.readObject();
System.out.println(user2.getUserName()+ "" +
user2.getPassword() + ""+ user2.getSex()); Xuliugen 123456 male}} public class User implements Serializable {private String userName; private String password; private String sex; // Full parameter constructor, get andsetMethod omitted}Copy the code
The object.out file is as follows (use UltraEdit to open it) :
Note: 0000000H-000000C0h in the figure above indicates the line number. 0-f denotes a column; The text after the line explains the line in hexadecimal; Those who are interested in the content expressed by the above bytecode can refer to the relevant data and look up the meaning of each character, which is not discussed here!
Just like in a.class file compiled by our Java code, each character represents a certain meaning. Serialization and deserialization are the processes that generate and parse the above characters!
Serialization diagram:
Deserialization diagram:
Iii. Relevant matters needing attention
In serialization, only the state of the object is saved, regardless of the method of the object;
2. When a parent class implements serialization, subclasses automatically implement Serializable interface without explicitly implementing Serializable interface;
3. When an instance variable of an object refers to another object, the reference object is serialized when the object is serialized.
4. Not all objects can be serialized, and there are many reasons why they can’t. For example:
-
For security reasons, such as an object has a private, public and other fields. For an object to be transferred, such as writing to a file or RMI transfer, the private and other fields of the object are not protected during serialization transmission.
-
For resource allocation reasons, such as socket and Thread classes, if they can be serialized, transferred, or saved, they cannot be re-allocated, and it is not necessary to do so.
Member data declared static and transient cannot be serialized. Static represents the state of the class and transient represents the temporary data of the object.
6. The serialization runtime is associated with each serializable class using a version number called serialVersionUID, which is used during deserialization to verify that the sender and receiver of the serialized object loaded a serialization-compatible class for the object. Give it an explicit value. Explicitly defining the serialVersionUID serves two purposes:
-
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;
-
In some cases, you don’t 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.
7. Java has many base classes that implement serializable interfaces, such as String,Vector, etc. However, some do not implement the Serializable interface;
If an object’s member variable is an object, then the object’s data members are also saved! This is an important reason serialization can solve deep copy;
Four,
After all, we already know how we usually use serialization and deserialization to operate, Java provides us with what interfaces to use, and we know what is serialization, deserialization and functions of a lot more than we initially know! We will continue to discuss and update the content!
Reference article:
1, zhidao.baidu.com/question/68…
2, blog.csdn.net/morethinkmo…
3, www.jianshu.com/p/edcf7bd2c…
4, blog.csdn.net/xiaocaidexu…
Java Backend Technology (ID: JavaITWork)1024, you can get it for free! Includes SSM, Spring family bucket, microservices, MySQL, MyCat, cluster, distributed, middleware, Linux, network, multi-threading, Jenkins, Nexus, Docker, ELK and so on free learning video, continue to update!