Serialization and deserialization of Java

Source: Internet
Author: User

    • The concept of serialization and deserialization

The process of converting an object to a sequence of bytes is called serialization of an object, and the process of reverting a sequence of bytes to an object is called deserialization.

Usage scenario: Saves a sequence of objects to a hard disk, usually in a file, and a sequence of files on a network that transmits objects.

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.

    • Serializing interfaces

Java objects, implement the serializable and Externalizable interface can be serialized, Externalizable interface inherits from Serializable interface, The object that implements Externalizable is fully controlled by its own serialization behavior, while the object implementing the Serializable interface takes the default serialization method.

Java.io.ObjectOutputStream represents the object output stream, which can be serialized by the WriteObject (object obj) method, and the resulting sequence of bytes is written to a target output stream;

Java.io.ObjectInputStream represents an object input stream, which can be read from a source using ReadObject () and then deserialized into an object.

    • Serialization and deserialization steps

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.

First, create an object:

Importjava.io.Serializable; Public classPersonImplementsSerializable {/**     *      */    Private Static Final LongSerialversionuid = 1L; Private intAge ; PrivateString name; PrivateString sex; Private intheight;  Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString Getsex () {returnsex; }     Public voidsetsex (String sex) { This. Sex =sex; }     Public intgetheight () {returnheight; }     Public voidSetHeight (intheight) {         This. Height =height; } @Override PublicString toString () {return"Person [age=" + Age + ", name=" + name + ", sex=" + Sex + ", height=" + height + "]"; }}

Serialization and deserialization:

ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;ImportCom.changjiang.test.testFuction.entity.Person; Public classtestserializable { Public Static voidMain (string[] args)throwsFileNotFoundException, IOException, classnotfoundexception {serialize ();    Deserializeperson (); }    Private Static voidSerialize ()throwsFileNotFoundException, IOException {person P=NewPerson (); P.setage (15); P.setname ("Game"); P.setheight (178); P.setsex ("Male"); ObjectOutputStream Ops=NewObjectOutputStream (NewFileOutputStream (NewFile ("E:/logs/person.txt")));        Ops.writeobject (P); System.out.println ("Completed object person serialization and output serialization results to file");    Ops.close (); }    Private Static voidDeserializeperson ()throwsFileNotFoundException, IOException, classnotfoundexception {objectinputstream ois=NewObjectInputStream (NewFileInputStream (NewFile ("E:/logs/person.txt"))); Person P=(person) ois.readobject (); System.out.println ("The deserialization of the completed object person and output the deserialized result to the console:" +p);    Ois.close (); }}

The result of the final output:

The object person is serialized and the serialized result is output to the file's completed object person's deserialization, and the deserialized result is output to the console: person [age = Name=game, Sex=male , height=178]

and the byte content in the output file:

Sr-com.changjiang.test.testfuction.entity.person        I AgeI heightl namet ljava/lang/string; L SEXQ ~ xp      Understand Gamet male
    • Serialversionuid

Classes that implement the Serializable interface if no serialversionuid are added to the class, the following warning prompt appears:

class Static Long

The compiler automatically prompts the following scenarios to resolve:

Selecting the former uses the default method to generate the ID (1L), which is a long value generated using the class name, interface name, method, and property.

How does it work?

In the previous example, we added a sentence to the person class:

    Private Static Long 1L;

And the person object is serialized into a text file in the Testserializable class, and if we modify the value of this ID at this point, the deserialization will get the exception information:

ExceptioninchThread"Main"Java.io.InvalidClassException:com.changjiang.test.testFuction.entity.Person; LocalclassIncompatible:stream Classdesc Serialversionuid =1, LocalclassSerialversionuid =2At java.io.ObjectStreamClass.initNonProxy (Objectstreamclass.java:617) at Java.io.ObjectInputStream.readNonProxyDesc (Objectinputstream.java:1622) at Java.io.ObjectInputStream.readClassDesc (Objectinputstream.java:1517) at Java.io.ObjectInputStream.readOrdinaryObject (Objectinputstream.java:1771) at Java.io.ObjectInputStream.readObject0 (Objectinputstream.java:1350) at Java.io.ObjectInputStream.readObject (Objectinputstream.java:370) at Com.changjiang.test.testFuction.test.TestSerializable.deSerializePerson (Testserializable.java: the) at Com.changjiang.test.testFuction.test.TestSerializable.main (Testserializable.java: -)

That is, the result of serialization is calculated according to id=1l, when this value is modified, the class in the file stream and the class in the classpath, that is, the modified class, is incompatible, in security considerations, the program throws an error, and refuses to load. Therefore, you want to modify the already serialized class and then deserialize the previous content, as long as the ID is the same as before and after.

The value of Serialversionuid is generated automatically by the Java Runtime Environment based on the internal 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. If the value display is not defined, the default value of the class's serialversionuid is entirely dependent on the implementation of the Java compiler, and compiling with different Java compilers for the same class may lead to different serialversionuid and possibly the same. So, to put it simply, to be compatible, to display a definition with a consistent ID, and to display an incompatible ID, it is highly recommended to give an unambiguous value to a serializable class in order to improve the independence and certainty of serialversionuid.

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.