Java object serialization learning notes

Source: Internet
Author: User
Tags object serialization
Document directory
  • Serialization mechanism:
  • Process object stream:
  • Custom serialization process:
  • Fully customized serialization process:
Currently, there are many articles on Object serialization on the network, but I found that there are too few articles describing the usage and principles in detail. I have contributed the learning notes I have written after my experience summary and practical use. I hope to do something for the prosperity of the entire Java Community.
The serialization process is to write the object into the byte stream and read the object from the byte stream. After converting the object state into word throttling, you can use Java. each byte stream class in the IO package saves it to a file, pipeline to another thread, or send object data to another host through network connection. Object serialization is simple and powerful, and has applications in RMI, socket, JMS, and EJB. Object serialization is not the most exciting topic in network programming, but it is very important and has many practical significance.
1. Object serialization can implement distributed objects. Main Applications: RMI uses objects to serialize services on remote hosts, just like running objects on local hosts.
Ii. Java object serialization not only retains the data of an object, but also recursively stores the data of each object referenced by the object. The entire Object layer can be written to the byte stream, stored in a file or transmitted over a network connection. Object serialization allows you to perform "Deep replication" on objects, that is, copying objects and referenced objects. Serializing an object may obtain the entire object sequence.
From the above description, we know that object serialization is an essential weapon in Java programming, so let's start from the basics and take a good look at its mechanism and usage.

Java serialization is relatively simple. You do not need to write custom code to save and restore the object state. Class objects implementing the java. Io. serializable interface can be converted to throttling or restored from byte streams without adding any code to the class. In rare cases, you need to customize the code to save or restore the object state. Note: Not every class can be serialized. Some classes cannot be serialized. For example, classes involving threads have very complex relationships with specific JVMs.
Serialization mechanism:

Serialization is divided into two parts:SerializationAndDeserialization. Serialization is the first part of this process. Data is decomposed into word throttling for storage in files or transmitted over the network. Deserialization is to open the byte stream and reconstruct the object. Object serialization not only converts the basic data type to a byte representation, but also restores data. To recover data, you must have an object instance that recovers data. The serialization process in objectoutputstream is connected to the byte stream, including the object type and version information. During deserialization, JVM generates an object instance with the header information, and then copies the data in the object byte stream to the object data member. Below we will explain in two parts:

Process object stream:

(Serialization and deserialization)

The Java. Io package has two classes for serialized objects. Objectoutputstream writes objects to byte streams, and objectinputstream reconstructs objects from byte streams.
Let's first understand the objectoutputstream class. Objectoutputstream class extends the dataoutput interface.
The writeobject () method is the most important method for Object serialization. If the object contains references from other objects, the writeobject () method recursively serializes these objects. Each objectoutputstream maintains a serialized object reference table to prevent sending multiple copies of the same object. (This is important) Because writeobject () can serialize the entire set of cross-referenced objects, the same objectoutputstream instance may be accidentally requested to serialize the same object. In this case, deserialization is performed instead of writing the object byte stream again.
Next, let's take a look at the objectoutputstream class from the example.

  1. // Serialize today's date to a file.
  2. Fileoutputstream F =NewFileoutputstream ("tmp ");
  3. Objectoutputstream S =NewObjectoutputstream (f );
  4. S. writeobject ("today ");
  5. S. writeobject (NewDate ());
  6. S. Flush ();

Now let's take a look at the objectinputstream class. It is similar to objectoutputstream. It extends the datainput interface. Methods In objectinputstream public methods for reading Basic Java Data Types in the image datainputstream. The readobject () method deserializes an object from a byte stream. Each call to the readobject () method returns the next object in the stream. Object byte streams do not transmit class bytecode, but include class names and signatures. When readobject () receives an object, JVM loads the class specified in the header. If this class is not found, readobject () throws classnotfoundexception. If you need to transmit object data and bytecode, you can use the RMI framework. Other methods of objectinputstream are used to customize the deserialization process.
Example:

  1. // Deserialize the string object and date object from the file
  2. Fileinputstream in =NewFileinputstream ("tmp ");
  3. Objectinputstream S =NewObjectinputstream (in );
  4. StringToday = (String) S. readobject ();
  5. Date = (date) S. readobject ();

Custom serialization process:

Serialization can usually be completed automatically, but sometimes it is necessary to control this process. Java can declare the class as serializable, but it can still manually control the data members declared as static or transient.
Example: A very simple serialization class.

  1. Public ClassSimpleserializableclassImplementsSerializable {
  2. StringStoday = "Today :";
  3. TransientDate dttoday =NewDate ();
  4. }

During serialization, all data members of the class should be serializable except those declared as transient or static. Declaring the variable as transient tells JVM that we are responsible for the serialization of the variable. After a data member is declared as a transient, it cannot be added to the object byte stream during the serialization process and no data is sent from the transient data member. During data deserialization, the data member (because it is part of the class definition) needs to be rebuilt, but does not contain any data, because the data member does not write any data to the stream. Remember, the object Stream does not serialize static or transient. Our class uses the writeobject () and readobject () methods to process these data members. When using the writeobject () and readobject () methods, read the data members in the write order.
Some code about how to use custom serialization is as follows:

  1. // Rewrite the writeobject () method to process transient members.
  2. Public VoidWriteobject (objectoutputstream outputstream)ThrowsIoexception {
  3. Outputstream. defaultwriteobject ();// Make the custom writeobject () method available
  4. Use built-in logic in automatic serialization.
  5. Outputstream. writeobject (osocket. getinetaddress ());
  6. Outputstream. writeint (osocket. getport ());
  7. }
  8. // Override the readobject () method to receive transient members.
  9. Private VoidReadobject (objectinputstream inputstream)ThrowsIoexception,Classnotfoundexception{
  10. Inputstream. defaultreadobject ();// Ultreadobject () supplement automatic serialization
  11. Inetaddress oaddress = (inetaddress) inputstream. readobject ();
  12. IntIport = inputstream. readint ();
  13. Osocket =NewSocket (oaddress, iport );
  14. IID = GETID ();
  15. Dttoday =NewDate ();
  16. }

Fully customized serialization process:

If a class is fully responsible for its own serialization, implement the externalizable interface instead of the serializable interface. The externalizable interface definition includes two methods: writeexternal () and readexternal (). These methods can be used to control how object data members write data into byte streams. when the class implements externalizable, the header is written into the object stream, and then the class is fully responsible for serialization and data restoration. Besides the header, there is no automatic serialization at all. Pay attention to this. Implementing the externalizable interface of declarative classes poses significant security risks. The writeexternal () and readexternal () methods are declared as public. Malicious classes can use these methods to read and write object data. Be especially careful when the object contains sensitive information. This includes using a secure connection or encrypting the entire byte stream. So far, we have learned the basic part of serialization. About order
The column-based advanced tutorial will be described later.

References: http://java.sun.com/j2se/1.3/docs/guide/serialization/spec/serialTOC.doc.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.