[Reserved] Java serialization and de-serialization

[Reserved] Java serialization and de-serialization

Source: https://www.cnblogs.com/anitinaj/p/9253921.html

Serialization and de-serialization in Java as a more basic knowledge, then you can talk about how serialization and de-serialization of the underlying is to achieve it?

First, the basic concept

1. What is the serialization and de-serialization

(. 1) refers to the Java Serialization converts Java objects to process a sequence of bytes, and to deserialize Java byte sequence refers to the recovery process of Java objects;

(2) serialization: object serialization main use is to save the object at the time of delivery and to ensure the integrity and delivery of the object. Serialization is the object into an ordered byte stream for transmission or stored in a local file on the network. Serialized byte stream to save the state of Java objects and associated descriptive information. The central role of serialization mechanism is the preservation and reconstruction of the object's state.

(3) deserialized: obtaining target client serialized byte stream or a file from the network, the stored byte stream according to the state of the object and description, deserialized by the reconstructed object.

(4) In essence, the sequence of the physical objects is written to the ordered state byte stream according to a certain format, deserialization is reconstructed object from an ordered byte stream to restore the state of the object.

2. Why do we need serialization and de-serialization

We know that when two processes communicate remotely, you can send each other various types of data, including text, images, audio, video, etc., and these data are in the form of binary sequences transmitted over the network.

So when two Java processes to communicate, ability to achieve the object transfer between process? The answer is yes! How to do it? This requires Java serialization and de-serialization of!

In other words, on the one hand, the sender need to convert the Java object is a sequence of bytes, and then transmitted on the network; the other hand, the recipient needs to recover the Java object from the byte sequence.

When we need to clarify why Java serialization and de-serialization, we naturally will want Java serialization benefits. First, to achieve its benefits persisted data, the data can be permanently stored serialization to disk (usually stored in the file), and second, the use of a sequence of remote communications, i.e. transfer the object on the network byte sequence.

In general it can be summarized as follows:

(1) Save persistent object storage target sequence of bytes to a local file or in a database;
(2) the object in a byte stream by serializing for transmission and reception in the network;
(3) the sequence of interprocess passing objects;

3, serialization algorithm will generally follow the steps to do the following things:

(1) The data output class object instance metadata related.
(2) Description superclass of class output recursively until no superclass.
(3) After the class metadata finished, start starts outputting the topmost object instance from a superclass of actual data values.
Data (4) output from the top down recursive instance

Two, Java how to implement serialization and de-serialization

1, JDK class library serialization and deserialization API

(1) java.io.ObjectOutputStream: object representing the output stream;

It writeObject (Object obj) method may serialize the object obj parameter specified, the resulting sequence of bytes written to a target output stream;

(2) java.io.ObjectInputStream: an object representing an input stream;

It readObject () method reads the source sequence of bytes in the input stream, then they become an object to deserialize, and return;

2, implement the serialization requirements

Only by achieving Serializable or Externalizable interface object class can be serialized, or throw an exception!

3, to realize Java object serialization and deserialization process

Assuming a User class, which is to serialize, you can have the following three ways:

(1) only if the User class implements Serializable interface can be serialized and deserialized in the following manner

ObjectOutputStream using default serialization, non-transient instance variables User object serialization.
ObjcetInputStream default deserialization mode, non-transient instance variables to the User object to be deserialized.

(2) only if the User class implements Serializable interface, and also defines readObject (ObjectInputStream in) and writeObject (ObjectOutputSteam out), then the following manner serialization and deserialization.

ObjectOutputStream calling User object writeObject (ObjectOutputStream out) method for serialization.
ObjectInputStream calls the method readObject (ObjectInputStream in) the User object deserialized.

(3) If the class implements Externalnalizable User Interface and User class must implement readExternal (ObjectInput in) and writeExternal (ObjectOutput out) method, the serialization and deserialization following manner.

ObjectOutputStream calling User object writeExternal (ObjectOutput out)) of the process sequence.
ObjectInputStream calls the User object readExternal (ObjectInput in) method to deserialize.

4, JDK library sequence of steps

Step a: output stream to create an object, it can be other types of packaging a target output stream, such as file output stream:

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\object.out"));

Step two: an object output stream via the writeObject () method write-targeted:

oos.writeObject(new User("xuliugen", "123456", "male"));

5, JDK class library deserialized step

Step a: input stream to create an object, it can be a package other types of input streams, such as file input stream:

ObjectInputStream ois= new ObjectInputStream(new FileInputStream("object.out"));

Step two: an object output stream by the readObject () method reads the object:

User user = (User) ois.readObject();

Description: In order to read data correctly, the deserialization is complete, sequential write must ensure that the output stream to the subject object from an object consistent with a reading target sequence flow input.

6, an exemplary serialization and deserialization

To better understand the sequence of Java and deserialization, cite a simple example as follows:

Copy the code

1 public class SerialDemo {
2  
3  
4  
5 public static void main(String[] args) throws IOException, ClassNotFoundException {
6  
7 //序列化
8  
9 FileOutputStream fos = new FileOutputStream("object.out");
10  
11 ObjectOutputStream oos = new ObjectOutputStream(fos);
12  
13 User user1 = new User("xuliugen", "123456", "male");
14  
15 oos.writeObject(user1);
16  
17 oos.flush();
18  
19 oos.close();
20  
21 //反序列化
22  
23 FileInputStream fis = new FileInputStream("object.out");
24  
25 ObjectInputStream ois = new ObjectInputStream(fis);
26  
27 User user2 = (User) ois.readObject();
28  
29 System.out.println(user2.getUserName()+ " " +
30  
31 user2.getPassword() + " " + user2.getSex());
32  
33 //反序列化的输出结果为:xuliugen 123456 male
34  
35 }
36  
37 }
38  
39  
40  
41 public class User implements Serializable {
42  
43 private String userName;
44  
45 private String password;
46  
47 private String sex;
48  
49 //全参构造方法、get和set方法省略
50  
51 }

Copy the code

object.out following documents (using UltraEdit open):

Write pictures described here

NOTE: the figure above 0000000h-000000c0h line number; 0-f indicates the column; the back of the line of text represents hexadecimal explain this line; the content of the above-described byte code expressed interest may control related information, Read about the meaning of each character represented not discuss here!

We like .class file after the Java code is compiled, each character represents a certain meaning. Serialization and de-serialization process is the process of generating and analysis of said character!

Serialization icon:

Write pictures described here

Deserialize shown:

Write pictures described here

Third, the relevant considerations

1, when the sequence of only the state of the object to be saved, but regardless of the method object;

2, when the parent class implements a serialization, subclasses automatically serialized, no explicit implements Serializable;

3, when the instance variables of an object reference other objects, the sequence of the object to be serialized referenced object;

4, not all objects can be serialized, as to why not, for many reasons, such as:

  • For security reasons, such as an object has a private, public and other field, for an object to be transferred, such as writing to a file, or by the RMI transport, etc., in the sequence of the transmission process, private and other objects of this domain is unprotected;
  • The reason allocation of resources, such as socket, thread class, if you can serialize, transmitted or stored, can not be re-allocation of resources to them, but, there is no need to be accomplished;

5, declared as static data members and transient types can not be serialized. Because the static state representative of the class, transient temporary data representative of the object.

6, a version number may be called serialVersionUID each class associated with the sequence, the sequence number for deserialization serialized object verify the sender and receiver for the object is loaded serialization runtime compatible with serialized class. As it gives a clear value. Explicitly defined serialVersionUID has two purposes:

  • In some cases, different versions of the desired class of sequences of compatibility, it is necessary to ensure that different versions of the class have the same serialVersionUID;
  • In some cases, different versions of the class do not want to serialize compatible, and therefore need to ensure that different versions of the class have different serialVersionUID.

7, Java Foundation Classes have already achieved many of the serializable interface, such as String, Vector and so on. But there are some not implement serializable interface;

8, if the member variables of an object is an object, then the data members of the object will be saved! This is an important reason for serialization can solve the deep copy;

When the sequence of all data members of the class should be serializable static or transient members except declared. The variable declared as transient tell JVM arguments we will be responsible for serialization. After the data members declared transient, the serialization process can not be added to the byte stream objects, data is not transmitted from the transient data members. When deserializing the data back, to reconstruct data members (because it is part of the class definition), but does not contain any data because the data members do not write any data to the stream. Remember, the object is not serialized stream static or transient. Our classes use writeObject () and readObject () method to handle these data members. When using writeObject () and readObject () method, but also pay attention to read the data sequentially written to the members

That these problems, how do we serialize and deserialize it?

Simple, that we have to deal separately and maybe has a type of variable, how do? It is to increase both a method in your class the emergence of such variables

Copy the code

1 private void writeObject(java.io.ObjectOutputStream out) throws IOException
2  
3 private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;
4 而对应于我们的类中添加的方法就是
5 
6  
7 public class SerialTest extends parent implements Serializable {
8  
9 //省略
10  
11 private void writeObject(ObjectOutputStream out) throws IOException {
12  
13 out.defaultWriteObject();
14  
15 out.writeInt(this.testStatic);
16  
17 out.writeInt(this.testTransient);
18  
19 }
20  
21 private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
22  
23 in.defaultReadObject();
24  
25 this.testStatic = in.readInt();
26  
27 this.testTransient = in.readInt();
28  
29 }
30  
31  
32  
33 }

Copy the code

When ObjectOutputStream a SerialTest to serialize objects, if the object has a writeObject () method, it will implement this method, otherwise by default serialization. In writeObjectt the object () method, can first call the ObjectOutputStream defaultWriteObject () method, the output stream such that the object to perform default serialization operation. Similarly deserialization can be drawn from the case, but this is defaultReadObject () method.

ObjectOutputStream.defaultWriteObject () : The current class of non-stationary (static) and non-transient fields (transient) to this stream.

ObjectInputStream.defaultReadObject () : stream read from the non-static and non-transient fields of the current class.

Externalizable role

For achieve Serializable class, in the sequence of the time, all of the non-static (static) and non-transient fields (transient) is automatically serialized, if there are some special requirements, we can fully manual control which fields are to be serialization, which do not serialized. Their life and death power rests in the hands of we. How to do? This time we should talk about the Externalizable class.

As long as Externalizable achieve this class, and replication

readExternal(ObjectInput in) throws IOException,CalssNotFoundException

writeExternal(ObjectOutput out) throws IOException,CalssNotFoundException

Can be, in readExternal (ObjectInput in) throws IOException, CalssNotFoundException process, and can determine which data is read from the object in.

writeExternal (ObjectOutput out) throws IOException, CalssNotFoundException process, can decide what data to write to go out.

Methods maybe one will ObjectOutputStream.writeObject (object) in the in; ObjectInputStream.readObject () automatically.


Reference article:

1、https://zhidao.baidu.com/question/688891250408618484.html
2、https://blog.csdn.net/morethinkmoretry/article/details/5929345
3、https://www.jianshu.com/p/edcf7bd2c085
4、https://blog.csdn.net/xiaocaidexuexibiji/article/details/22692097

Guess you like

Origin www.cnblogs.com/jiading/p/12013449.html