Java Fundamentals: Serialization (Serializable) and deserialization

Source: Internet
Author: User

What are the applications that involve serialization and deserialization when learning ObjectOutputStream and objectinputstream in IO?

First, the concept

Serialization: The process of converting an object to a sequence of bytes, called the serialization of an object.

Deserialization: The process of reverting a sequence of bytes to an object, called the deserialization of an object.

Second, the role

There are two main uses:

1. Permanently save the object's byte sequence to the hard disk, that is, the memory data (object) persisted processing.

2. You can transfer the character sequence of an object on the network, and the object is no longer restricted to local use.

Regardless of the purpose, it is in fact the state of the various objects in memory (i.e. instance variables, not methods), and the state of the saved objects can be read again. This is a mechanism provided by Java to preserve the state of an object.

Third, the application

As mentioned at the beginning, there are two classes of serialized objects in the Java.io package, namely:ObjectOutputStream writes the object to the byte stream,objectinputstream The byte stream to the object.

It is important to note that the serialized object must implement the serializable or Externalizable interface.

Example 1: (for readability, exceptions are disposed of):

1 ImportJava.io.File;2 ImportJava.io.FileInputStream;3 ImportJava.io.FileOutputStream;4 ImportJava.io.ObjectInputStream;5 ImportJava.io.ObjectOutputStream;6 Importjava.io.Serializable;7 8  Public classTest {9      Public Static voidMain (string[] args)throwsexception{TenPerson p =NewPerson ("Zhangsan", 20); One Serializeperson (p); Aperson P1 =Deserializeperson (); -System.out.println (p1);//results Print zhangsan:20.  -     } the  - //Serialization of -     Private Static voidSerializeperson (Object obj)throwsException { -ObjectOutputStream out=NewObjectOutputStream (NewFileOutputStream (NewFile ("C:\\obj.txt"))); + out.writeobject (obj); -System.out.println ("Serialization succeeded"); + out.close (); A     } at      - //deserialization -     Private StaticPerson Deserializeperson ()throwsException { -ObjectInputStream in =NewObjectInputStream (NewFileInputStream ("C:\\obj.txt")); -person P1 =(person) in.readobject (); -System.out.println ("Deserialization succeeded"); in in.close (); -         returnP1; to     } +      - } the  *  $ classPersonImplementsSerializable {Panax Notoginseng //Note that if you do not specify Serialversionuid, serialization is done by default, and Serialversionuid is generated.  - //However, if the code in the class is modified later, the serialization-generated serialversionuid will also change, and the deserialization will fail with an exception.  the     Private Static Final LongSerialversionuid = 1L; +     PrivateString name; A     Private intAge ; the Person () { +SYSTEM.OUT.PRINTLN ("Null parameter constructor"); -     } $      PublicPerson (String name,intAge ) { $System.out.println ("Parametric constructor"); -          This. Name =name; -          This. Age =Age ; the     } -     Wuyi      PublicString toString () { the         returnName+ ":" +Age ; -     } Wu}

The result of the above code operation is:

Parametric constructors
Serialization succeeds
Deserialization succeeded
Zhangsan:20

As you can see from the results, when deserializing, it does not work with the constructor of the person class, but instead creates the person object based on the serialized data.

Note that the default Serialversionuid value is the Java runtime, which is automatically generated based on the inner details of the class. If the source code of the class is modified and then recompiled, the value of the serialversionuid of the newly generated class file may also change. The default value of the Serialversionuid class is entirely dependent on the implementation of the Java compiler, and compiling with different Java compilers for the same class may lead to different Serialversionuidand possibly the same. To improve the independence and certainty of serialversionuid, it is strongly recommended that the definition serialversionuid be displayed in a serializable class, giving it a definite value.

Explicit definition of Serialversionuid can be achieved for two purposes:

1. If you want a different version of the class (the class has been modified) serialization, can be successfully deserialized (compatible), you need to ensure that classes of different versions of the class have the same serialversionuid;

2. If you do not want the different versions of the class to be serialized and can be deserialized successfully, let the different versions of the class have different serialversionuid.

Example 2:

Serialize First:

1  Public classTestSerialze {2      Public Static voidMain (string[] args)throwsexception{3Person p =NewPerson ("Zhangsan", 20);4 Serializeperson (p);5     }6 7 //Serialization of8     Private Static voidSerializeperson (Object obj)throwsException {9ObjectOutputStream out=NewObjectOutputStream (NewFileOutputStream (NewFile ("C:\\obj.txt")));Ten out.writeobject (obj); OneSystem.out.println ("Serialization succeeded"); A out.close (); -     } - } the  -  - classPersonImplementsSerializable { - //Note that if you do not specify Serialversionuid, serialization is done by default, and Serialversionuid is generated.  + //However, if the contents of the class are modified, the serialization produces a new serialversionuid, which is different from the original, when deserialization fails and an exception occurs.  -     Private Static Final LongSerialversionuid = 1L; +     PrivateString name; A     Private intAge ; at //static members belong to a class and cannot be serialized.  -     Private Static intcount; - //transients cannot be serialized either.  -     transient Private intkey; -      - Person () { inSYSTEM.OUT.PRINTLN ("Null parameter constructor"); -     } to      PublicPerson (String name,intAge ) { +System.out.println ("Parametric constructor"); -          This. Name =name; the          This. Age =Age ; *count++; $key++;Panax Notoginseng     } -      the      PublicString toString () { +         returnName+ ":" +age+ "..." +count+ "..." +key; A     } the}

Post-deserialization:

ImportJava.io.FileInputStream;ImportJava.io.ObjectInputStream; Public classTestdeserialze { Public Static voidMain (string[] args)throwsexception{Object obj=Deserializeobject ();    System.out.println (obj); }    Private StaticObject Deserializeobject ()throwsException {ObjectInputStream in=NewObjectInputStream (NewFileInputStream ("C:\\obj.txt")); Object obj=In.readobject (); System.out.println ("Deserialization succeeded");        In.close (); returnobj; }}

The result of deserialization is:

Deserialization succeeded
zhangsan:20...0...0

It can be seen that member variables modified by static and transient cannot be serialized.

Java Fundamentals: Serialization (Serializable) and deserialization

Related Article

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.