java serialization and deserialization principle underlying implementation

Source: What serialization and de-serialization of the underlying implementation principle?

 

First, the basic concept
1 What is 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) the sequence of **: ** object serialization main use is in the transmission and storage when the object to ensure the integrity of the object and transmitted. 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 from a file on the network, according to the state of the object and the description information stored in the byte stream by the reconstructed object deserialization .

 (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:

public class SerialDemo {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //序列化
        FileOutputStream fos = new FileOutputStream("object.out");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        User user1 = new User("xuliugen", "123456", "male");
        oos.writeObject(user1);
        oos.flush();
        oos.close();
        //反序列化
        FileInputStream fis = newThe FileInputStream ( "object.out" ); 
        the ObjectInputStream OIS = new new the ObjectInputStream (FIS); 
        the User user2 = (the User) ois.readObject (); 
        System.out.println (user2.getUserName () + "" +  
            user2.getPassword () + "" + user2.getSex ());
         // deserialized output is: MALE xuliugen 123456 
    } 
} 

public  class the User the implements the serializable {
     Private String the userName;
     Private String password;
     Private String Sex;
     // All parameters constructor , get, and set methods are omitted
}

object.out following documents (using UltraEdit open):

  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:

 Deserialize shown:

 

Third, the relevant precautions
 1, when serialized, only the state of the object is 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;


Fourth, the deserialization vulnerability

Related deserialization vulnerability can access relevant information, not described here.

 

Guess you like

Origin www.cnblogs.com/myseries/p/11931512.html