Serialization and deserialization of Java objects

Source: Internet
Author: User
Tags object serialization

I. The concept of serialization and deserialization

  The process of converting an object to a sequence of bytes is called serialization of an object .
  The process of reverting a sequence of bytes to an object is called deserialization of the object .
There are two main uses for serialization of objects:
1) The object's byte sequence is permanently saved to the hard disk, usually stored in a file;
2) A sequence of bytes that transmits an object over the network.

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.

Two serialization APIs in the JDK class library

Java.io.ObjectOutputStream represents an object output stream, and its writeobject (object obj) method serializes the Obj object specified by the parameter and writes the resulting sequence of bytes to a target output stream.
Java.io.ObjectInputStream represents an object input stream, and its readobject () method reads a sequence of bytes from a source input stream, deserializes them into an object, and returns them.
Only objects of classes that implement the serializable and Externalizable interfaces can be serialized. The Externalizable interface inherits from the serializable interface, and the class that implements the Externalizable interface controls the serialization behavior entirely by itself, whereas classes that implement the serializable interface can take the default serialization method.
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.

Examples of object serialization and deserialization:

Define a person class to implement the Serializable interface

1 Import java.io.Serializable; 2  3/** 4  * <p>ClassName:Person<p> 5  * <p>description: Test object serialization and deserialization <p> 6  * @ Author XUDP 7  * @version 1.0 V 8  * @createTime 2014-6-9 pm 02:33:25 9  */10 public class person implements Seria lizable {     /**13      * Serialization ID14      */15     private static final long Serialversionuid = -5809782578272943999l ;     private int age;17     private string name;18     private string sex;19 public     int getage () {         Return age;22     }23 public     string GetName () {         return name;26     }27     -public string getsex () {         return sex;30     }31 public     void Setage (int. age) {         this.age = age;34     }35     void SetName (string name) {PNS         this.name = name;38     }39     -public void Setsex (String sex) {$         this.sex = sex;42     }43}

  Serializing and deserializing a person class object

 1 Import java.io.File; 2 Import Java.io.FileInputStream; 3 Import java.io.FileNotFoundException; 4 Import Java.io.FileOutputStream; 5 Import java.io.IOException; 6 Import Java.io.ObjectInputStream; 7 Import Java.io.ObjectOutputStream; 8 Import Java.text.MessageFormat; 9/**11 * <p>classname:testobjserializeanddeserialize<p>12 * <p>description: Serialization and deserialization of test objects <p& GT;13 * @author XUDP14 * @version 1.0 V15 * @createTime 2014-6-9 PM 03:17:2516 */17 public class Testobjserializeanddes         erialize {public static void main (string[] args) throws Exception {Serializeperson ();//serialization of person object 21 Person P = Deserializeperson ();//Reverse Sequence Perons object System.out.println (Messageformat.format ("Name={0},age={1},s Ex={2} ", P.getname (), P.getage (), P.getsex ())); 24}25 26/* *27 * Methodname:serializeperson * Description: Serialize Person Object * @author xudp30 * @throws FILENOTFO UNDEXCEPTION31 * @throws IOException32 */33 private static void Serializeperson () throws Filenotfoundexceptio n,34 IOException {The person person = new person (), Person.setname ("GaCl"), and the PNS person. Setage, Person.setsex ("male"), the ObjectOutputStream object output stream, stores the person object in the E-drive's Person.txt file, completing the order of the Person object Column operation ObjectOutputStream oo = new ObjectOutputStream (New FileOutputStream ("E:/person. TXT ")); Oo.writeobject (person), System.out.println (" Person object serialization succeeded!       "); Oo.close ();}46/**48 * Methodname:deserializeperson * Description: Anti-sequence Perons object 50 * @author xudp51 * @return52 * @throws Exception53 * @throws IOException54 */55 Private Stat IC Person Deserializeperson () throws Exception, IOException {objectinputstream ois = new ObjectInputStream (new FileInputStream New File ("E:/person.txt")); Ois.readobject (person) (); System.out.println ("The person object is deserialized successfully! "), return person;61}62 63}

The result of the code operation is as follows:

The serialized person succeeds in generating an Person.txt file on the e-disk, and the deserialization of the person is reading the e-disk Person.txt into a person object

Threethe role of Serialversionuid

S?e?r?i?a?l? V?e?r?s?i?o? n? U? I? D?:????????????, all the classes that implement the Serializable interface have a static variable that represents the serialized version identifier.

1 private static final long Serialversionuid

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

  

Clicking on the mouse will pop up the dialog box that generates Serialversionuid, as shown in:

  

There are two ways to build Serialversionuid:

The serialversionuid generated in this way are 1L, for example:

1 private static final long serialversionuid = 1L;

Serialversionuid generated in this way are generated based on the class name, interface name, method, and property, for example:

1 private static final long serialversionuid = 4603642343377807741L;

Once added, the warning prompt does not appear as follows:

  

Pull so much, then Serialversionuid (serialized version number) What is the use of it, we use the following example to illustrate the role of Serialversionuid, see the following code:

 1 Import java.io.File; 2 Import Java.io.FileInputStream; 3 Import java.io.FileNotFoundException; 4 Import Java.io.FileOutputStream; 5 Import java.io.IOException; 6 Import Java.io.ObjectInputStream; 7 Import Java.io.ObjectOutputStream; 8 Import java.io.Serializable; 9 public class Testserialversionuid {One to ten public static void Main (string[] args) throws Exception {Seri Alizecustomer ();//serialization of the Customer object to customer customer = Deserializecustomer ();//Reverse Sequence Customer object System.out      . println (Customer),}17/**19 * Methodname:serializecustomer * Description: Serialization of Customer Objects 21 * @author XUDP22 * @throws FileNotFoundException23 * @throws IOException24 */25 private static void S Erializecustomer () throws filenotfoundexception,26 IOException {Customer customer = new Customer ("G ACL "," +//ObjectOutputStream object output stream ObjectOutputStream oo = new ObjectOutputStream (New Fileoutputstr EAM (New File ("E:/customer.txt")), Oo.writeobject (Customer), System.out.println ("Cus Tomer Object Serialization succeeded! "); Oo.close ();}35/**37 * Methodname:deserializecustomer * Description: anti-sequence customer XUDP40 * @author * @return41 * @throws Exception42 * @throws IOException43 */44 Private Static Customer Deserializecustomer () throws Exception, IOException {objectinputstream ois = new Objectinputstr EAM (FileInputStream new File ("E:/customer.txt")); customer customer = (Customer) Ois.rea Dobject (); System.out.println ("The Customer object is deserialized successfully! "); return customer;50}51}52/**54 * <p>classname:customer<p>55 * <p>description: The customer implements the serializable interface, which can be serialized <p>56 * @author xudp57 * @version 1.0 V58 * @createTime 2014-6-9 pm 04:20:1759 */ The class Customer implements Serializable {//customer classes are not defined SerialversionUID62 private string name;63 private int age;64 (string name, int age) {. Name = name;67 This.age = age;68}69/*71 * @MethodName toString72 * @Description Override the object class T Ostring () method * @author xudp74 * @return string75 * @see java.lang.object#tostring () */77 @Overr ide78 public String toString () {return "name=" + name + ", age=" + age;80}81}

Operation Result:

Both serialization and deserialization were successful.

Let's modify the customer class and add one more sex attribute, as follows:

1 class Customer implements Serializable {2     //customer class does not define SERIALVERSIONUID 3     private String name; 4     private int age; 5  6     //Newly added sex attribute 7     private String sex; 8      9 public     Customer (String name, Int. age) {Ten         THIS.name = name;11         this.age = age;12     }13     public     Customer (String name, int age,string sex) {15< C14/>this.name = name;16         this.age = age;17         this.sex = sex;18     }19 (     /*21)      * @MethodName ToString22      * @Description rewrite the ToString () method of the object class at      XUDP24 * @author      * @return string25      * @see Java.lang.object#tostring ()      */27     @Override28 public     String toString () {         return "name=" + Name + ", age=" + age;30     }31}

The following exception information is thrown when the deserialization operation is performed:

1 Exception in thread "main" java.io.InvalidClassException:Customer; 2 Local class Incompatible:3 stream Classdesc Serialversionuid = -88175599799432325, 4 local class Serialversionuid = 51 82532647273106745

That is, 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. So what if we really have a need to add a field or method after serialization? What should I do? That is to appoint Serialversionuid. In the Testserialversionuid example, the Serialversionuid of the customer class is not specified, and the Java compiler automatically gives the Class A digest algorithm, similar to the fingerprint algorithm, as long as the file has one more space, The resulting UID will be quite different, and it can be guaranteed that in so many classes, the number is unique. So, after adding a field, because there is no explicit serialversionuid, the compiler generated a UID for us, of course, and the previous saved in the file is not the same, so there are 2 serialized version number inconsistent error. Therefore, as long as we specify the Serialversionuid, we can after serialization, to add a field, or method, without affecting the later restore, the restored object can still be used, but also more methods or properties can be used.

The following continues to modify the customer class, specifying a serialversionuid for customer, with the following modified code:

1 class Customer implements Serializable {2     /** 3      * SERIALVERSIONUID (serialized version number) defined in the Customer Class 4      */5      Private static final long serialversionuid = -5182532647273106745l; 6     private string name; 7     private int age; 8  9     //Newly added sex attribute     //private String sex;11     Public Customer (String name, Int. age) {         this.name = name;14         this.age = age;15     }16     +/* Public Customer (String name, int age,string sex) {         this.name = name;19         this.age = age;20         this.sex = sex;2 1     }*/22     /*24      * @MethodName toString25      * @Description override the ToString () method of the object class      * @author Xudp27      * @return string28      * @see java.lang.object#tostring ()      */30     @Override31     Public String toString () {         return "name=" + name + ", age=" + age;33     }34}

Re-executes the serialization operation, serializes the customer object to the local hard disk's Customer.txt file store, then modifies the customer class, adds the sex attribute, and modifies the customer class code as follows:

1 class Customer implements Serializable {2     /** 3      * SERIALVERSIONUID (serialized version number) defined in the Customer Class 4      */5      Private static final long serialversionuid = -5182532647273106745l; 6     private string name; 7     private int age; 8  9     //Newly added sex attribute--     private string sex; Public     Customer (String name, Int. age) {         this.name = name;14         this.age = age;15     }16 + Public     Customer (String name, int age,string sex) {         this.name = name;19         this.age = age;20         This.sex = sex;21     }22     /*24      * @MethodName toString25      * @Description overriding the ToString () method of the object class 26      * @author xudp27      * @return string28      * @see java.lang.object#tostring ()      */30     @Override31 Public     String toString () {         return "name=" + name + ", age=" + age;33     }34}

To perform the deserialization operation, this time the deserialization succeeds, as follows:

  

Iv. Value of Serialversionuid

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.
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 serialversionuid and 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 .

There are two ways to explicitly define SERIALVERSIONUID:
1, in some cases, you want different versions of the class to be serializable compatible, so you need to ensure that the different versions of the class have the same serialversionuid;
2. In some cases, you do not want different versions of the class to be serializable compatible, so you need to ensure that different versions of the class have different serialversionuid.

Serialization and deserialization of Java objects

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.