Java object serialization learning notes (transferred from: javaresearch.org beejoy original)

zhaozj2021-02-12  169

There are a lot of articles on object serialization on the network, but I found that there is too little article in detail usage and principles. I contribute to the study notes written by experience summary and practical use. I hope to do something for the prosperity of the entire Java community.

The serialization process is that the object writes the word throttle and reads the object from the byte stream. After converting the object state into byte stream, you can save it to the file in the various byte streams in the Java.IO package, and the pipe is sent to another thread or through the network connection to another host. Object serialization is very simple, powerful, in RMI, Socket, JMS, and EJBs have applications. Object Serialization issues are not the most exciting topics in network programming, but it is quite important and has many practical significance.

One: Object Series can achieve distributed objects. Main applications, for example: RMI To use the target serialization to run the service on the remote host, just like running the object on the local machine.

Second: Java object serialization not only retains data of an object, but recursively saving the data of each object referenced by the object. The entire object hierarchy can be written in the word stream, and can be saved in a file or transfer it on a network connection. The "deep copy" of the object can be made using object serialization, ie the object itself and the referenced object itself are copied. Seed-grained objects may result in the entire object sequence.

From the above description, we know that object serialization is a must-have weapon in Java programming, so let us start from the basics, learn its mechanism and usage.

Java serialization is relatively simple, usually does not need to write custom code for saving and recovering object status. Implementing a class object for java.io.Serializable interfaces can convert to word throtlation or recover from byte streams, and do not need to add any code in the class. There is only a few cases to customize the code to save or restore the object status. Here you should pay attention to: Not each class can be serialized, some categories are unable to serialize, such as a very complex relationship between the class involving threads and a particular JVM.

Serialization mechanism:

Serialization is divided into two parts:

Serialization

Anti-sequentialization. Serialization is the first part of this process, decomposing data into a byte stream in order to be stored in a file or transmitted on the network. Define sequence is to open byte stream and refactor the object. Object serialization not only converts the basic data type into byte, sometimes it is necessary to recover data. Recovery data requires an object instance for recovery data. The serialization process in ObjectOutputStream is connected to byte stream, including object types and version information. When deserialization, the JVM generates an object instance with head information, and then copies data in the object word stream into the object data member. Below we are divided into two parts:

Treatment target stream: (serialization process and deserialization process)

Java.io package has two sequential objects. ObjectOutputStream is responsible for writing objects into byte stream, ObjectInputStream from byte stream rebuild objects.

Let's understand the ObjectOutputStream class. ObjectOutputStream class extension DataoutPUT interface.

The WriteObject () method is the most important method for object serialization. If the object contains references to other objects, the WriteObject () method recursively serializes these objects. Each ObjectOutputStream maintains a serialized object reference table to prevent multiple copies of the same object. (This is very important) Since WriteObject () can serialize the object of the entire group, the same ObjectOutputStream instance may be unclearly requested sequentially the same object. At this time, the reverse reference serialization is performed, not the object word stream again.

Below, let us learn this class from ObjectOutputStream from the example.

// Serialized Today's Date into a file.

FileOutputStream f =

New FileOutputStream

"TMP"); ObjectOutputStream S =

New ObjectOutputStream (f);

S.WriteObject

"Today");

S.WriteObject

New Date ());

S.flush ();

Now let's learn about ObjectInputStream. It is similar to ObjectOutputStream. It expands the DataInput interface. Method in ObjectInputStream reads a disclosure of Java basic data types in DataInputStream. The readObject () method is reorganized from the byte stream. Each time you call the ReadObject () method back the next Object. The object word is not transmitted bytes, but includes class names and their signatures. ReadObject () When the object is received, the JVM is loaded into the class specified in the header. If you can't find this class, readObject () throws ClassNotFoundException. If you need to transfer object data and bytecodes, you can use the RMI framework. The remaining methods of ObjectInputStream are used to customize the reverse sequencer process.

The example is as follows:

// Reverse sequencing String objects from the file and Date object

FileInputStream in =

New fileInputstream

"TMP");

ObjectInputStream S =

New ObjectInputStream (in);

String Today = (String) S.ReadObject ();

Date Date = (date) s.readObject ();

Customized serialization process:

Serialization can usually be completed automatically, but sometimes it is possible to control this process. Java can declare class declared as Serializable, but can still manually control data members for Static or Transient.

Example: A very simple serialization class.

public

Class SimpleSerializableClass

IMPLEMENTS SERIALIZABLE {

String stoday =

"Today:";

TRANSIENT DATE DTTODAY =

New Date ();

}

When serialization, all of the data members of the class should serialize members of the TRANSIENT or STATIC. Declaring variables to transient telling JVM we will be responsible for sequentialization. After declaring the data as Transient, the serialization process cannot add it to the object word throttle without data sent from the Transient data member. When the back data is reversed, the data member is to be rebuilt (because it is part of the class definition), but does not contain any data because this data member does not write any data in the stream. Remember, the object stream is not serialized Static or Transient. Our classes use WriteObject () to handle these data members with the readObject () method. When using WriteObject () and readObject () methods, pay attention to read these data members in the order of writing.

Some code on how to use custom sequence is as follows:

// Rewrite the WriteObject () method to handle the member of Transient.

public

Void WriteObject (ObjectOutputStream OutputStream)

THROWS IOEXCEPTION {

OutputStream.default ();

/ / Method to customize the WriteObject () method

Using the logic built into automatic serialization.

OutputStream.writeObject (Osocket.GetinetAddress ());

OutputStream.writeInt (Osocket.get ();

// Rewrite the ReadObject () method to receive the member of Transient.

Private

Void ReadObject (ObjectInputStream InputStream)

THROWS IEXCEPTION, ClassNotFoundException {

InputStream.defaultReadObject ();

// defaultReadObject () Supplemental automatic serialization

Inetaddress Oaddress = (inetaddress) InputStream.ReadObject ();

INT iPort = InputStream.readint ();

Osocket =

New Socket (Oaddress, iPort);

IID = GetId ();

DTTODAY =

New Date ();

}

Fully customized serialization process:

If a class is fully responsible for your serialization, you implement the Externalizable interface instead of the serializable interface. The Externalizable interface definition includes two methods WriteExternal () with readExternal (). Using these methods can control the object data member to write byte stream. When you implement ExternalizAble, the header is written in the target stream, and then the class is fully responsible for serialization and recovery data, except for the header, there is no automatic serialization at all. I have to pay attention here. The declaration class will have significant security risks in the externalizable interface. WriteExternal () is declared as public, and malicious classes can be read and write object data with these methods. If the object contains sensitive information, be careful. This includes using security cacles or encrypts the entire byte stream. To this, we learned the sequenceful basic part of knowledge. On the order

The advanced tutorial is later described later.

Reference: http://java.sun.com/j2se/1.3/docs/guide/serialization/spec/serialtoc.doc.html

转载请注明原文地址:https://www.9cbs.com/read-6969.html

New Post(0)