Java Object Serialization Learning notes

Source: Internet
Author: User
Tags date definition class definition header implement interface object serialization string
Java Objects | Notes there are many articles on the web about object serialization, but I find that there are too few articles detailing usage and principles. I have a summary of their experience and practical use of the experience written in the study notes to contribute to everyone. Hoping to do something about the prosperity of the entire Java community.
The process of serialization is the object writes the byte stream and reads the object from the byte stream. After you convert an object state to a byte stream, you can save it to a file with a variety of byte streams in the Java.io package, pipe to another thread, or send the object data to another host over a network connection. Object serialization is very simple and powerful, and is used in RMI, sockets, JMS, and EJBs. The problem of object serialization is not the most exciting subject in network programming, but it is very important and has many practical meanings.
One: Object serialization can implement distributed objects. Main applications For example: RMI uses object serialization to run a service on a remote host as if it were running on a local machine.
Two: Java object serialization preserves not only the data of one object, but also the data of each object referenced by the object recursively. The entire object hierarchy can be written to a byte stream and can be saved in a file or passed on a network connection. Object serialization enables the "deep copy" of objects, that is, the copying of objects themselves and the objects they refer to. Serializing an object can get the entire sequence of objects.
From the above description, we know that object serialization is a necessary weapon in Java programming, so let's start with the basics and learn about its mechanism and usage.

Java serialization is simpler and usually requires no custom code to save and recover the state of the object. A class object that implements the Java.io.Serializable interface can be converted to a byte stream or recovered from a byte stream, without adding any code to the class. In rare cases, custom code is required to save or restore object state. Note here: Not every class is serializable, and some classes are not serializable, for example, a class involving threads has a very complex relationship with a particular JVM.

Serialization mechanism:


Serialization is divided into two parts: serialization and deserialization. Serialization is the first part of the process that decomposes data into byte streams for storage in files or on the network. Deserialization is the opening of a byte stream and the construction of an object. Object serialization not only converts basic data types to byte representations, but sometimes restores data. Recovery data requires an object instance that recovers data. The serialization process in ObjectOutputStream is connected to a byte stream, including the object type and version information. When deserialized, the JVM generates an object instance with the header information, and then copies the data in the object byte stream to the object data member. Here are two major sections to illustrate:

To process an object stream:

(Serialization process and deserialization process)

The Java.io package has two classes of serialized objects. ObjectOutputStream is responsible for writing the object to the byte stream and ObjectInputStream the object from the byte stream.
Let's get to the ObjectOutputStream class first. The ObjectOutputStream class extends the 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 the objects. Each ObjectOutputStream maintains a serialized object reference table, preventing multiple copies of the same object from being sent. (This is important) because WriteObject () can serialize an entire set of cross-referenced objects, the same ObjectOutputStream instance may be accidentally requested to serialize the same object. In this case, the deserialization is serialized instead of the object byte stream being written again.
Let's take a look at the ObjectOutputStream class from the examples below.
    1. Serializes today ' s date to a file.
    2. FileOutputStream f = new FileOutputStream ("TMP");
    3. ObjectOutputStream s = new ObjectOutputStream (f);
    4. S.writeobject ("Today");
    5. S.writeobject (New Date ());
    6. S.flush ();

Now, let's take a look at this class of ObjectInputStream. It is similar to the ObjectOutputStream. It extends the Datainput interface. The public method of reading Java basic data types in the method mirror DataInputStream in ObjectInputStream. The ReadObject () method deserializes an object from a byte stream. Each call to the ReadObject () method returns the next object in the stream. The object byte stream does not transmit the bytecode of the class, but includes the class name and its signature. ReadObject () When an object is received, the JVM loads the class specified in the header. If this class is not found, the ReadObject () throws ClassNotFoundException, and if you need to transfer the object data and bytecode, you can use the RMI framework. The remainder of the ObjectInputStream method is used to customize the deserialization process.
Examples are as follows:
    1. Deserialize a string object and a Date object from a file
    2. FileInputStream in = new FileInputStream ("TMP");
    3. ObjectInputStream s = new ObjectInputStream (in);
    4. String today = (string) s.readobject ();
    5. Date date = (date) s.readobject ();

Customizing the serialization process:



Serialization can usually be done automatically, but sometimes this process may have to be controlled. Java can declare a class as serializable, but it can still manually control data members declared as static or transient.
Example: A very simple serialization class.
    1. public class Simpleserializableclass implements serializable{
    2. String stoday= "Today:";
    3. Transient date dttoday=new date ();
    4. }

When serialized, all data members of a class should be serializable except for members declared as transient or static. Declaring a variable as transient tells the JVM that we are responsible for serializing the arguments. When a data member is declared as transient, the serialization process cannot be added to the object byte stream, and no data is sent from the transient data member. When the data is deserialized later, the data member is rebuilt (because it is part of the class definition) but does not contain any data because the data member does not write any data to the stream. Remember that 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, also note that the data members are read in the order in which they are written.
Some of the code on how to use custom serialization is as follows:
  1. Override the WriteObject () method to handle the members of the transient.
  2. public void WriteObject (ObjectOutputStream outputstream) throws ioexception{
  3. Outputstream.defaultwriteobject ()///Make the Custom WriteObject () method can
  4. Take advantage of the logic built into automatic serialization.
  5. Outputstream.writeobject (Osocket.getinetaddress ());
  6. Outputstream.writeint (Osocket.getport ());
  7. }
  8. Override the ReadObject () method to receive members of the transient.
  9. private void ReadObject (ObjectInputStream inputstream) throws ioexception,classnotfoundexception{
  10. Inputstream.defaultreadobject ();//defaultreadobject () Supplemental automatic serialization
  11. InetAddress oaddress= (inetaddress) inputstream.readobject ();
  12. int Iport =inputstream.readint ();
  13. Osocket = new Socket (oaddress,iport);
  14. Iid=getid ();
  15. Dttoday =new Date ();
  16. }

Fully customizable serialization process:


If a class is to be fully responsible for its own serialization, implement the Externalizable interface instead of the serializable interface. The Externalizable interface definition consists of two methods writeexternal () and readexternal (). These methods allow you to control how object data members write to a byte stream. When a class implements Externalizable, the header is written to the object stream, and then the class is fully responsible for serializing and restoring the data member, which is not automatically serialized except for the header. Here you have to pay attention. Declaring a class implements the Externalizable interface can have significant security risks. The Writeexternal () and the Readexternal () method are declared public, and the malicious class can use these methods to read and write object data. Be extra careful if the object contains sensitive information. This includes using Secure Sockets or encrypting entire byte streams. To this, we learned the basics of serialization. About Preface
The advanced tutorial of the column, later again.


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.