Java Serialization (serialization)

Source: Internet
Author: User
Tags object serialization

About the Java serialization of the article on the internet has enough, write about the Java serialization here is a summary of their own on this aspect, combined with the previous development experience and online information, wrote this article, for oneself is has the role of consolidating memory, also hope to have a certain help to everyone.

First, what is serialization (serialization)?

Serialization is a mechanism provided by Java that transforms an object into a sequence of bytes, storing the object's data in a sequence of bytes, the type of object's information, and the type of data stored in the object. Serialization is essentially the "state" of the object that will be saved for later use by the program or transmitted over the network to another host. In general, the generation period of an object depends on whether the program is executing, and the serialization is able to save the object on a disk or network so that the object can live between calls to the program.

Second, the purpose of serialization

The use of serialization to save the state of an object is primarily to support two major features:

    1. Java's remote method invocation (RMI), which is capable of surviving objects on other machines, is used as if it were local. When sending a message to a remote object, it is necessary to transfer the parameters and return values through object serialization.
    2. In Java beans, you must use object serialization.
Three, the basic example of serialization

The most basic way to implement serialization in Java is to implement the Serializable interface, which is the serializable interface and does not contain any methods. To serialize an object, you must first create some Outoutstream objects and then encapsulate them inside the ObjectOutputStream object, where ObjectOutputStream provides the WriteObject () method, which is called to serialize the object.

Deserialization is the restoration of a sequence of bytes generated from an object to an object, the need to encapsulate the InputStream object in a ObjectInputStream object, and then call ReadObject to read the object.

The following is a basic example of object serialization:

Class Pet ImplementsSerializable {PrivateString name; PublicPet (String name) {this.name =Name } publicString toString () {returnName }}public class Person implementsSerializable {private static final long Serialversionuid = 1L; private intAge PrivateString name; PrivatePet Ownpet; Public person (String name, intAge, Pet ownpet) {this.name =Name This.age =Age This.ownpet = Ownpet;} @Override public  String toString () {return ' person [age= ' + Age + ', name= "+ name +", ownpet= "+  Ownpet +" ] ";} public static void Main (string[] args) throws  FileNotFoundException, IOException, classnotfoundexception {person P1 = new Person ("Person1", +, New Pet ("Dog" )); person P2 = new Person ("Person2", New Pet ("Cat" )); Object serialization ObjectOutputStream out = new ObjectOutputStream (New  FileOutputStream ("Person.out" )); System.out.println ("Save objects:" ); Out.writeobject (p1); Out.writeobject (p2); Out.close (); Object deserialization ObjectInputStream in = new ObjectInputStream (New  FileInputStream ("Person.out" )); System.out.println ("Recovering objects:" ); P1 =  (person) in.readobject (), p2 =  (person) in.readobject (); System.out.println (p1); System.out.println (p2); }}

The results of the above procedure are:

Save objects:recovering Objects:person [age=47, Name=person1, ownpet=Dog]person [age=34, Name=person2, OwnPet=cat] 

As seen from the above results, object serialization not only serializes objects that call WriteObject (), but also keeps references to objects that call WriteObject (), and saves those referenced objects, so object serialization can automatically save the object's associated reference object. To ensure the integrity of object information, it is possible to use object serialization for deep replication of objects.

Note: The implementation of the Serializable interface object deserialization does not call the constructor, which restores the sequence of bytes directly to the object. This class must be guaranteed in the classpath during serialization, Person.class in this instance, or thrown classnotfoundexception.

Third, realize Externalizable interface

Another way to serialize is to implement the Externalizable interface, which provides the following default methods for the Externalizable interface:

    void Writeexternal (ObjectOutput out) throws IOException;    void Readexternal (ObjectInput in) throws IOException, ClassNotFoundException;

The user must implement both methods by themselves, and in the method you can control the serialization, such as to allow some member properties to not be serialized, as in the following example:

public class Test implementsexternalizable {private intI PrivateString s; PublicTest () {System.out.println ("test default constructor"); } public Test (String x, intA) {System.out.println ("Test (String x, int a)"); s =X i =A } publicString toString () {return S +I } public void Writeexternal (ObjectOutput out) throwsIOException {System.out.println ("blip3.writeexternal"); You must does this: Out.writeobject (s); Out.writeint (i);} public void Readexternal (ObjectInput in) throws  IOException, classnotfoundexception {System.out.println (" Blip3.readexternal "); You must do this:s =  (String) in.readobject (), i =  in.readint ();} public static void Main (string[] args) Throws  FileNotFoundException, IOException, classnotfoundexception {System.out.println ("Constructorint objects : "); Test test = new Test ("A String", + ); SYSTEM.OUT.PRINTLN (B3); Object serialization ObjectOutputStream out = new ObjectOutputStream (New  FileOutputStream ("Test.out" )); System.out.println ("Save objects:" ); Out.writeobject (B3); Out.close (); Object deserialization ObjectInputStream in = new ObjectInputStream (New  FileInputStream ("Test.out" )); System.out.println ("Recovering test:" ); B3 =  (Test) In.readobject ()}}             

The result of the above program operation is:

Constructorint objects:test (string x, int a) a string,Save objects:Test.writeExternalRecovering test:test Default constructortest.readexternal  

It can be seen from the results that in order to be able to serialize an object, you must not only write the object member variable in the Writeexternal () method, but also read the member variable in the Readexternal () method. The default constructor method is called during deserialization of an object.

Four, transient key words

Transient can control the member variables, prevent the leakage of sensitive information, of course, the implementation of the above Externalizable method can also complete the function, but must control all the properties of the serialization, more complex. The transient (instantaneous) keyword can be used to turn off serialization of the field, as shown in the following example:

public class Logon implementsSerializable {Private Date date = newDate (); PrivateString username; Private transient String password; Public  Logon (string name, string password) {this.username =  name; this.password =  password;} PU Blic  String toString () {return "Logon info: \ n Username:" + username + "\ n Date:" +  date + "\ n Password:" +  password;} public static void Main (string[] args) throws  FileNotFoundException, IOException, ClassNotFound Exception {Logon A = new logon ("Hulk", "Mylittlepony" ); SYSTEM.OUT.PRINTLN ("Logon a =" +  a); ObjectOutputStream o = new ObjectOutputStream (New  FileOutputStream ("Out/logon.out" )); O.writeobject (a); O.close (); Gets the serialized data objectinputstream in = new ObjectInputStream (New  FileInputStream ("Out/logon.out" )); System.out.println ("Recovering object at" + New  Date ()); A =  (Logon) in.readobject (); SYSTEM.OUT.PRINTLN ("Logon a =" +  a);}           

The results of the above procedure are:

Logon Info:  username:hulk date:wed Jan 21:55:16 CST password:mylittleponyrecovering object at Wed Jan 2 0 21:55:16 CSTLogon info:  username:hulk date:wed Jan 21:55:16 CST password:null  

From the results, it is known that the password field is hidden and not serialized.

V. Replace the realization of externalizable

In the object serialization process for serialization control, if the implementation of the Externalizable interface, you must implement the serialization control of each property, too complex, how to replace it? By implementing the Serializable interface and adding two methods, as long as these two methods are provided, they are used instead of the default serialization mechanism. The two method signatures are as follows:

private void WriteObject (ObjectOutputStream stream) throws IOException

private void ReadObject (ObjectInputStream stream) throws IOException, ClassNotFoundException

In the above two methods can call the default processing method, you can also control the serialization of the property, the instance code is as follows:

public class Serialctl implementsSerializable {PrivateString A; Private transientString b; PublicSerialctl (string aa, String bb) {THIS.A = "not trnsient:" +Cay this.b = "Transient:" +bb } public String toString () {return a + "\ n" +  b;} private void WriteObject (ObjectOutputStream stream) throws  I oexception {stream.defaultwriteobject (); Stream.writeobject (b);} private void ReadObject (ObjectInputStream stream) Throws  IOException, classnotfoundexception {stream.defaultreadobject (); b =  (String) Stream.readobject ();} public static void Main (string[] args) throws  FileNotFoundException, IOException, classnotfoundexception { Serialctl sc = new Serialctl ("Test1", "Test2" ); System.out.println ("before:\n" +  SC); Bytearrayoutputstream buf = new  bytearrayoutputstream (); ObjectOutputStream o = new  objectoutputstream (BUF); O.writeobject (SC);//Get serialized data ObjectInputStream in = new Object InputStream (New  Bytearrayinputstream (Buf.tobytearray ())); sc =  (serialctl) in.readobject (); System.out.println ("after:\n" +  SC);}           

Results of the above procedure:

Before:not Trnsient:Test1Transient:Test2After:Not Trnsient:Test1Transient:Test2
Vi. Summary

In summary, the simplest serialization is the implementation of the serializable interface, if for the security of sensitive information, you can use the transient keyword. If you want to control the serialization process in one step, we recommend implementing the Serializable interface and adding two serialization methods, and customizing the implementation method.

Java Serialization (serialization)

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.