Serialization and deserialization of Java objects

Source: Internet
Author: User

serialization and deserialization of Java objects

In Java, if we want to save the instantaneous state value of an object so that we can get those values at the next use, or persist the object, or use RMI (remote method call), or pass an object over the network, we need to serialize the object and serialize it. As long as we implement the Serializable interface, the interface is a tag interface (tag interface), that is, there is no method inside, its main function is to tell the JVM that the class object can be serialized.

In general, many classes of objects implement the Serializable interface, but some objects are not serializable, such as database-related connection objects, file objects and so on, it is meaningless to save the state values of these objects, Therefore, object does not implement the Serializable interface is also the reason, if you want to serialize the object, as long as we implement the Serializable interface, a class of the parent class implements the serializable interface, its subclasses will implement the interface by default, in turn, If its subclass needs to be serialized, its parent class must implement the Serializable interface.

Serialization is to save the state of an object, so a variable of static type is not serialized, because it is meaningless to save its value, it will change dynamically during the run, for a variable of a reference type, or for a reference variable, and when we serialize the object, we serialize it. We just have to make sure that they all implement the serializable interface.

In the process of serialization, if for some variables, we do not want to save its value, then we add the keyword transient before the reference variable or the original variable name, so that the field will not be serialized, when the deserialization reverts to the object, Its default value is null (the field is the object type) or the default value of the original type (the original type variable).

At deserialization time, the JVM assembles the serialized object and then opens up space in the heap to generate the object of the appropriate type, which does not call the constructor in the process. Of course, if we don't want to use the default serialization provided by Java, we can simply implement the Externalizable interface, and when the object is read, the parameterless constructor of the serialized class is called to create a new object, and then the values of the fields of the saved object are populated into the new object, respectively. With this interface, the details of the serialization need to be done by the programmer.

Examples are as follows:

 PackageCom.test;Importjava.io.Serializable;/** * Created by siege on 2015-07-28. * * Public  class  person implements Serializable {    Private transient  intnum=3;Private transientString description="Hello";Private Static  intCountPrivateString name;Private intAge Public  Person(String name,intAge) {count++; This. name = name; This. Age = Age; }@Override     PublicStringtoString() {return "Name"+":"+name+", Age:"+age+", Count:"+count+", Num:"+num+", Description:"+description; }}
 PackageCom.test;Importjava.io.*;/** * Created by siege on 2015-07-28. * * Public  class serializabletest {     Public Static void Main(string[] args) {Person person1=NewPerson ("Siege1", -); Person person2=NewPerson ("Siege2", +); Person person3=NewPerson ("Siege3", A);Try{FileOutputStream fos=NewFileOutputStream ("C:\\test\\person.out"); ObjectOutputStream objectoutputstream=NewObjectOutputStream (FOS);            Objectoutputstream.writeobject (Person1);            Objectoutputstream.writeobject (Person2);            Objectoutputstream.writeobject (Person3);        Objectoutputstream.close (); }Catch(Java.io.IOException e)        {E.printstacktrace (); }Try{FileInputStream fin=NewFileInputStream ("C:\\test\\person.out"); ObjectInputStream objectinputstream=NewObjectInputStream (Fin);Try{person p1= (person) objectinputstream.readobject ();                Person p2= (person) objectinputstream.readobject ();                Person p3= (person) objectinputstream.readobject ();                System.out.println (p1);                System.out.println (p2);            SYSTEM.OUT.PRINTLN (p3); }Catch(ClassNotFoundException e)            {E.printstacktrace (); }        }Catch(IOException e)        {E.printstacktrace (); }    }}

The output results are as follows:

Name:siege1,age:20,count:3,num:0,description:null
Name:siege2,age:21,count:3,num:0,description:null
Name:siege3,age:22,count:3,num:0,description:null

Thus, the value of the static variable is removed from the class variable after we deserialize it into the object, and the variable of the transient type is not serialized, and the deserialized value is the default value.

If the person does not implement the Serializable interface, it will appear

Java.io.NotSerializableException

Error.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Serialization and deserialization of Java objects

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.