Java object serialization and deserialization

Source: Internet
Author: User

I. Why serialization?

Before introducing it, we need to first understand the object lifecycle. We know that all objects in Java exist in the heap memory, and the heap memory can be recycled occasionally by the garbage collector. From the creation of an object to the collection of the object, this is the lifecycle of the Java object, that is, the Java object only exists in this period of time.

The garbage collector recycles the object, which means that the memory occupied by the member variables in the object is recycled. This means that we will no longer get any content of the object, because it has been destroyed, of course we can re-create the object, but all the attributes of the object are re-initialized. Therefore, if we need to save the status of an object and restore it for a certain period of time in the future, the state of the object must be saved before the object is destroyed, that is, the object is recycled by the garbage collector. To save the object status, we can use files, databases, or serialization. Here we mainly introduce Object serialization. We need to know about this, because Object serialization can be used not only to save the object state (Object persistence), but also to call RMI remotely in Java, if you want to transmit objects in the network, you must serialize the objects. For RMI, I will post a special introduction.

In summary, the main reason for Object serialization is to achieve Object Persistence and network transmission. Here we will only introduce how to save the object state through object serialization.

Next we will introduce how to serialize objects through a simple example.

Ii. How to serialize objects

Assume that we want to save the name, age, and height member variables of a Person class three objects. Here is a simple example.

Let's take a look at the Person class. to serialize an object of a class, the class must implement the Serializable interface. From the Java API, we find that this interface is an empty interface, that is, no methods are declared in this interface.

import 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;}}

Next, let's take a look at how to serialize it. This mainly involves Java's I/O content. It mainly uses two classes: fileoutputstream and objectoutputstream. fileoutputstream is used to output bytes to files, objectoutputstream calls the writeobject method to convert the object into data that can be written into the stream. The whole process is as follows: objectoutputstream converts the object to be serialized to a certain data type, and then connects to a disk file through fileoutputstream, then the data converted by the object is converted into byte data and then written to the disk file. The code below is as follows:

Import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. objectoutputstream; public class mytestser {/*** Java object 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", 28,178 ); try {// a file output stream and an object output stream are required. The file output stream is used to output bytes to the file, the object output stream is used to output the object as a byte objectoutputstream out = new objectoutputstream (New fileoutputstream ("person. ser "); out. writeobject (zhangsan); out. writeobject (Lisi); out. writeobject (wangwu); out. close ();} catch (ioexception e) {e. printstacktrace ();}}}

Iii. Object deserialization

The purpose of our storage is to restore the service. Next we will look at the code after deserialization:

Import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. IOException; import java. io. objectInputStream; import java. io. objectOutputStream; public class MyTestSer {/*** Java object 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", 28,178 ); try {// a file output stream and an object output stream are required. The file output stream is used to output bytes to the file, the object output stream is used to output the object as a byte 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 two = (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 result is 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 deserialization is also very simple. The main stream used is FileInputstream and ObjectInputstream, which correspond to the stream used for storage. In addition, we can see from the result order that the object obtained after deserialization is in the same order as that during serialization.

Iv. Summary

Object serialization mainly aims to save the object state (member variable ).

The main stream used for serialization is FileOutputStream and ObjectOutputStream. FileOutputStream is mainly used to connect to a disk file and write bytes to the disk file. ObjectOutputStream is mainly used to write the object into bytes.

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

The purpose of saving the status is to restore the stored content at some time in the future, which can be achieved through deserialization. The object deserialization process is opposite to serialization. The two main streams used are FileInputstream and ObjectInputStream.

The order of the deserialized objects is the same as that of the stored objects.

5. Supplement

I. Adding: the example above is very simple. The member variables to be saved are either of the basic type or the String type. However, sometimes the member variables may be of the reference type, which is complicated. That is, when an object is serialized, the object referenced by the referenced variable in the object will be serialized at the same time, in addition, if a variable is referenced in the object, the object will also be serialized. In summary, during serialization, the objects corresponding to all referenced variables in the object will be serialized at the same time. This means that the Serializable interface must be implemented for all referenced variable types. Of course, serialization of other objects is automatically performed. Therefore, we only need to ensure that all the reference types in it implement the Serializable interface. If not, an exception will be thrown during compilation. If the serialized object contains a member variable that does not implement Serializable, you can use the transient keyword to skip this member variable during serialization. The keyword transient allows you to automatically skip the member variables modified by transient during serialization. These variables are restored to the default values during deserialization.

Supplement 2: If a class implements the Serializable interface, its subclass will be automatically programmed and Serializable. This is easy to understand and inherit from.

Supplement 3: During deserialization, the constructor of the object is not called. This is understandable. If the constructor is called, will the object state be re-initialized.

4. Object serialization aims to save the object state, that is, the member variable of the object, so static variables are not serialized.

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.