Serialization and deserialization

Source: Internet
Author: User
Tags object serialization

Http://www.cnblogs.com/xdp-gacl/p/3777987.html

Java Basic Learning summarize serialization and deserialization of--java objects concepts of serialization and deserialization

  The process of converting an object to a sequence of bytes is called serialization of an object .
  The process of reverting a sequence of bytes to an object is called deserialization of the object .
There are two main uses for serialization of objects:
1) The object's byte sequence is permanently saved to the hard disk, usually stored in a file;
2) A sequence of bytes that transmits an object over the network.

In many applications, some objects need to be serialized to leave the memory space and stay on the physical hard disk for long-term storage. For example, the most common is the Web server session object, when there are 100,000 users concurrent access, there may be 100,000 session objects, memory may be unbearable, so the Web container will be some seesion first serialized to the hard disk, and so on, Restore the objects that were saved to the hard disk in memory.

When two processes are communicating remotely, each other can send various types of data. Regardless of the type of data, it is transmitted over the network in the form of a binary sequence. The sender needs to convert the Java object to a sequence of bytes to be transmitted over the network, and the receiver needs to revert the byte sequence back to the Java object.

Two serialization APIs in the JDK class library

Java.io.ObjectOutputStream represents an object output stream, and its writeobject (object obj) method serializes the Obj object specified by the parameter and writes the resulting sequence of bytes to a target output stream.
Java.io.ObjectInputStream represents an object input stream, and its readobject () method reads a sequence of bytes from a source input stream, deserializes them into an object, and returns them.
Only objects of classes that implement the serializable and Externalizable interfaces can be serialized. The Externalizable interface inherits from the serializable interface, and the class that implements the Externalizable interface controls the serialization behavior entirely by itself, whereas classes that implement the serializable interface can take the default serialization method.
Object serialization consists of the following steps:
1) Create an object output stream, which can wrap a different type of target output stream, such as a file output stream;
2) writes an object through the WriteObject () method of the object output stream.

The steps for deserializing an object are as follows:
1) Create an object input stream, which can wrap a different type of source input stream, such as a file input stream;
2) The object is read through the ReadObject () method of the object input stream.

http://blog.csdn.net/fenglibing/article/details/8905490

1. What is serialization ?

This is simply to preserve the state of various objects in memory (i.e., instance variables, not methods), and to read the saved object state again. Although you can save object states in a variety of ways, Java provides you with a mechanism that should be better than your own to preserve the state of objects, which is serialization.

2. What situations require serialization

A) When you want to save the state of an object in memory in a file or in a database;

b) When you want to use sockets to transfer objects on the network;

c) When you want to transfer objects through RMI;

6, the related matters needing attention

A) When serializing, only the state of the object is saved, regardless of the object's method;

b) When a parent class is serialized and the subclass is automatically serialized, no explicit implementation of the serializable interface is required;

c) When an instance variable of an object refers to another object, the object is serialized as well.

D) Not all objects can be serialized, and there are a number of reasons why not, such as:

1. Security reasons, such as an object has Private,public and other fields, for a transmission of the object, such as writing to a file, or RMI transmission, etc., during the serialization of the transfer process, the object's private domain is not protected.

2. Resource allocation reasons, such as the Socket,thread class, can be serialized, transmitted or saved, and cannot be re-allocated, and there is no need to implement this.

Detailed Description:

The process of serialization is that the object writes the byte stream and reads the object from the byte stream. After you convert the object state to a byte stream, you can save it to a file with various byte stream classes in the Java.io package, pipe to another thread, or send the object data to another host over a network connection. The object serialization feature is simple and powerful, with applications in RMI, sockets, JMS, and EJBs. Object serialization problem is not the most exciting topic 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 to use object serialization to run a service on a remote host, just as you would when running an object on a local machine.

Two: Java object serialization preserves not only the data of an object, but also the data of each object referenced by the object. You can write the entire object hierarchy to a stream of bytes that can be saved in a file or passed on a network connection. Object serialization allows you to "deep copy" the object, which is to copy the object itself and the referenced object itself. Serializing an object may get the entire sequence of objects.

From the above narrative, we know that object serialization is an essential weapon in Java programming, so let's start with the basics and learn about its mechanics and usage.

Java serialization is relatively straightforward and typically does not require writing custom code to save and restore object state. The class object that implements the Java.io.Serializable interface can be converted into a byte stream or recovered from a byte stream without adding any code to the class. Only rare cases require custom code to save or Restore object state. Note here that not every class can be serialized, and some classes cannot be serialized, such as a thread-related class with a very complex relationship to a particular JVM.

Serialization mechanism:

Serialization consists of two parts: serialization and deserialization . Serialization is the first part of this process that decomposes data into a byte stream for storage in a file or on a network. Deserialization is the opening of a byte stream and refactoring the object. Object serialization not only converts the base data type to a byte representation, but sometimes restores the data. Recovering data requires an object instance that has recovery data. The serialization process in ObjectOutputStream is connected to a byte stream, including object type and version information. When deserializing, the JVM generates an object instance with header information and then copies the data in the object stream into the object data member. Here we have two parts to illustrate:

To process the object flow:

(Serialization process and deserialization process)

The Java.io package has a class of two serialized objects. The ObjectOutputStream is responsible for writing the object to the byte stream, ObjectInputStream the object from the byte stream.

Let's get to know 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, so the same ObjectOutputStream instance may be accidentally requested to serialize the same object. At this point, the deserialization is serialized instead of being written to the object byte stream again.

Let's take a look at the ObjectOutputStream class from the examples below.

Serialize today's date into a file.

FileOutputStream f = new FileOutputStream ("TMP");//Create a "TMP" data file containing the recovery object (that is, the object to deserialize information)

ObjectOutputStream s = new ObjectOutputStream (f);

S.writeobject ("Today"); Writes a String object;

S.writeobject (New Date ()); Writes a transient object;

S.flush ();

Now, let's get to know the ObjectInputStream class. It is similar to ObjectOutputStream. It extends the Datainput interface. The method in the ObjectInputStream image DataInputStream reads the public method of the Java base data type. 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 class's bytecode, 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, then ReadObject () throws ClassNotFoundException, and if you need to transfer object data and bytecode, you can use the RMI framework. The remaining methods of ObjectInputStream are used to customize the deserialization process.

Examples are as follows:

Deserializes a string object and a Date object from a file

FileInputStream in = new FileInputStream ("TMP");

ObjectInputStream s = new ObjectInputStream (in);

String today = (string) s.readobject (); Recover objects;

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

To customize the serialization process:

Serialization can usually be done automatically, but this process can sometimes be controlled. Java can declare a class as serializable, but it can still manually control data members that are declared static or transient.

Example: A very simple serialization class.

public class Simpleserializableclass implementsserializable{

String stoday= "Today:";

Transient date dttoday=new date ();

}

When serializing, 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. After a data member is declared as transient, the serialization process cannot add it to the object byte stream, and no data is sent from the transient data member. When the data is deserialized, 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 flow of objects does not serialize static or transient. Our classes use the WriteObject () and ReadObject () methods to process these data members. When using the WriteObject () and ReadObject () methods, also note that these 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:

Override the WriteObject () method to handle the members of the transient.

public void WriteObject (ObjectOutputStream outputstream) throws ioexception{

Outputstream.defaultwriteobject ();//enable the custom WriteObject () method to

Take advantage of the logic built into automatic serialization.

Outputstream.writeobject (Osocket.getinetaddress ());

Outputstream.writeint (Osocket.getport ());

}

Override the ReadObject () method to receive members of the transient.

private void ReadObject (ObjectInputStream inputstream) throwsioexception,classnotfoundexception{

Inputstream.defaultreadobject ();//defaultreadobject () Supplemental automatic serialization

Inetaddressoaddress= (inetaddress) inputstream.readobject ();

int Iport =inputstream.readint ();

Osocket = new Socket (oaddress,iport);

Iid=getid ();

Dttoday =new Date ();

}

From:http://www.e800.com.cn/articles/2011/0804/492750.shtml

Serialization and deserialization

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.