Serialization and deserialization of Java

Source: Internet
Author: User
Tags object serialization

First, why to serialize

Before we introduce, we need to understand the life cycle of the object, we know the life cycle of the Java object, that is, The remote method call RMI in Java will also be used, In order to transfer objects in the network, you have to serialize the object, and I'll have a special introduction to the RMI opportunity.

Simply summed up, the main reason for the object serialization is to implement object persistence and network transmission, here first only how to save the state of the object through object serialization.

Let's take a simple example to illustrate how to serialize objects.

Second, how to do object serialization

Suppose we want to save Three member variables of the name, age, andheight of some three objects of the person class, but this is a simple example.

We first look at the person class, to serialize the object of a class, then it is necessary to implement the Serializable interface, from which we find that the interface is an empty interface, that is, the interface does not declare any method.

java. Io. Serializable;public class Person implements Serializable {int age;int height; String Name;public Person (string name, int age, int height) {this.name = Name;this.age = Age;this.height = height;}}


Now let's look at how to serialize, which is mainly related to java . Io. Fileoutputstream;import java . Io. Ioexception;import java . Io. Objectoutputstream;public class Mytestser {/** * serialization and deserialization */public static void Main (string[] args) {person Zhangsan = new Person ("Zhangsan", 30, 170); Person Lisi = new Person ("Lisi", 35, 175); Person Wangwu = new Person ("Wangwu", "178"); try {//requires a file output stream and an object output stream; The file output stream is used to output bytes to a file. The object output stream is used to output the object as bytes objectoutputstream out = new ObjectOutputStream (New FileOutputStream ("Person.ser")); Out.writeobject ( Zhangsan); Out.writeobject (Lisi); Out.writeobject (WANGWU); Out.close ();} catch (IOException e) {e.printstacktrace ();}}}
Three, deserialization of an object

The main purpose of our storage is to re-use it, let's take a look at the following deserialized code:

ImportJava. Io. Fileinputstream;importJava. Io. Fileoutputstream;importJava. Io. Ioexception;importJava. Io. Objectinputstream;importJava. Io. Objectoutputstream;public class Mytestser {/** *serialization and deserialization of */public static void Main (string[] args) {person Zhangsan = new Person ("Zhangsan", 30, 170); Person Lisi = new Person ("Lisi", 35, 175); Person Wangwu = new Person ("Wangwu", "178"); try {//requires a file output stream and an object output stream; The file output stream is used to output bytes to a file. The object output stream is used to output the object as bytes objectoutputstream out = new ObjectOutputStream (New FileOutputStream ("Person.ser")); Out.writeobject ( Zhangsan); Out.writeobject (Lisi); Out.writeobject (WANGWU);} catch (IOException e) {e.printstacktrace ();} try {objectinputstream in = new ObjectInputStream (New FileInputStream ("Person.ser")); Person one = (person) in.readobject (); Person: (person) in.readobject (); Person three = (person) in.readobject (); System.out.println ("Name:" +one.name + "Age:" +one.age + "Height:" +one.height); System.out.println ("Name:" +two.name + "Age:" +two.age + "Height:" +two.height); System.out.println ("Name:" +three.name + "Age:" +three.age + "Height:" +three.height);} catch (Exception e) {e.printstacktrace ();}}}


The output results are as follows:

Name:zhangsan age:30 height:170name:zhangsan age:35 height:175name:zhangsan age:28 height:178


From the added code we can see that the deserialization is also very simple, the main use of the flow is fileinputstream and ObjectInputStream exactly with the stream used to correspond. In addition, from the order of results we can see that the order of the objects obtained after deserialization is consistent with the order of serialization.

Iv. Summary

The main purpose of the object serialization is to save the state of the object (member variable).

The main stream used for serialization is FileOutputStream and objectoutputstream. FileOutputStream is primarily used to connect disk files and write bytes out to the disk file;ObjectOutputStream is primarily used to write objects as data that can be converted to bytes.

To serialize an object of a class, the class must implement the Serializable interface, which is only a flag that tells the JVM that the object of the class can be serialized. If a class does not implement the Serializable interface, the class object cannot be serialized.

The purpose of the save state is to restore the saved content at some point in the future, which can be done by deserialization. The deserialization process of an object is the reverse of serialization, with the main two streams being fileinputstream and ObjectInputStream.

The order in which the objects are deserialized is consistent with the order in which they were saved.

V. Supplementary

Add one: the example above is very simple, the member variables to be saved are either basic types orString type. But sometimes a member variable might be a reference type, which is a bit more complicated. That is, when you want to serialize an object, the object referenced by the reference variable in the object is also serialized, and if there is a reference variable in that object, the object will also be serialized. In summary, the object of all reference variables in the object will be serialized at the time of serialization. This means that reference variable types are also implemented serializable interface. Of course, the serialization of other objects is automatic. So we just have to make sure that the reference type is all implemented serializableserializabletransient keyword, let the member variable be skipped when serializing. Use the keyword can let you automatically skip the transient member variables that are modified to revert to the default values when deserializing.

Add two: If a class implements the Serializable interface, its subclasses will automatically be programmed to serialize, this good understanding, inheritance.

Add three: When deserializing , does not invoke the object's constructor, it is also understood that if the constructor is called, the state of the object is not re-initialized it.

Add four: We say that the object is serialized to hold the object's state, that is, the object's member variable, so the static variable is not serialized.

Serialization and deserialization of Java

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.