Serialization and deserialization of Java objects detailed introduction _java

Source: Internet
Author: User
Tags object serialization serialization

Last weekend, the basics of Java have done a collation, where the Java serialization and deserialization of the data in detail, here to make a note, I hope to also help to read this article friends.

First, the concept of serialization and deserialization

The process of converting an object to a sequence of bytes is called serialization of objects.
The process of restoring a byte sequence to an object is called deserialization of an 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 transfer the byte sequence of the object on the network.

In many applications, some objects need to be serialized so that they leave the memory space and stay in the physical hard drive for long-term preservation. 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 too much, so the Web container will be some seesion first serialized to the hard disk, and so on, Then restore the objects saved in the hard disk to memory.

When two processes are communicating remotely, they can send different 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 into a byte sequence to be routed over the network, and the receiver needs to revert the byte sequence back to the Java object.

Ii. serialization APIs in JDK class libraries

Java.io.ObjectOutputStream represents an object output stream whose WriteObject (object obj) method serializes the Obj object specified by the parameter and writes the resulting byte sequence to a target output stream.

Java.io.ObjectInputStream represents an object input stream whose 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, and the class that implements only the serializable interface can use the default serialization method.

Object serialization consists of the following steps:

1 Create an object output stream that can wrap a different type of target output stream, such as a file output stream;
2 The object is written through the WriteObject () method of the object output stream.

The steps to deserialize an object are as follows:

1 Create an object input stream that can wrap a different type of source input stream, such as a file input stream;
2 The object is read by 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 Public
class person implements Serializable {   /**   * Serialization ID/   private static final long Serialversionuid = -5809782578272943999l;
-   private int age;
The   private String name;
A   private String sex;
The 
public   int Getage () {Return to age     ;
Public   String getName () {+ return     name;
The   public   String getsex () {     sex;
The   public   void setage (int age) {     this.age = age;
The   public   void SetName (String name) {     this.name = name;
The   public   void setsex (String sex) {     this.sex = sex;
43}

Serialization and deserialization of a person class object

Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;

Import Java.text.MessageFormat; /** * <p>ClassName:TestObjSerializeAndDeserialize<p> * <p>description: Serialization and reverse sequence of test objects <p> * @aut Hor XUDP * @version 1.0 V * @createTime 2014-6-9 PM 03:17:25/public class Testobjserializeanddeserialize {public static void Main (string[] args) throws Exception {Serializeperson ();//serialization of person object person P = Deserializeperson (); Reverse Sequence Perons Object System.out.println (Messageformat.format ("name={0},age={1},sex={2}", P.getname ()
  , P.getage (), P.getsex ()); /** * Methodname:serializeperson * Description: Serializing the Person object * @author xudp * @throws filenotfoundexce ption * @throws IOException * * private static void Serializeperson () throws FileNotFoundException,
      IOException {Person person = new person ();
    Person.setname ("GaCl");
    Person.setage (25);
    Person.setsex ("male"); ObjectOutputStream the object output stream, storing the person object in the Person.txt file on e disk, completing the serialization of the person object ObjectOutputStream oo = new objectoutputst
    Ream (New FileOutputStream ("E:/person.txt"));
    Oo.writeobject (person); System.out.println ("The Person object serialized successfully!")
    ");
  Oo.close (); /** * Methodname:deserializeperson * Description: Reverse Sequence perons Object * @author xudp * @return * @throws exc Eption * @throws IOException * * private static person Deserializeperson () throws Exception, IOException {obje
    Ctinputstream ois = new ObjectInputStream (New FileInputStream ("E:/person.txt"));
    person who = (person) ois.readobject (); System.out.println ("The Person object deserialized successfully!")
    ");
  return person; }

}

The results of the code run are as follows:

The serialized person succeeded in generating a Person.txt file on E disk, while the deserialized person was reading the E-disk Person.txt became a person object

third, the role of Serialversionuid

S e r i a l V e R S i o n U i D: It is a serialized version number in literal sense, and a class that implements the Serializable interface has a static variable that represents the serialized version identifier

Private static final long Serialversionuid

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

  

Click on the mouse will pop up to generate Serialversionuid dialog box, as shown in the following figure:

  

There are two ways to generate SERIALVERSIONUID:

The serialversionuid generated in this manner is 1L, for example:

private static final long serialversionuid = 1L;

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

Private static final long serialversionuid = 4603642343377807741L;

The warning will not appear after you add it, as follows:

  

So many, then Serialversionuid (serialized version number) What is the use of it, we use the following example to illustrate the role of Serialversionuid, look at 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 public static void main (string[] args) throws Exception {serial Izecustomer ()//serialized Customer Object customer = Deserializecustomer ();//Reverse Sequence Customer object System.out.println
(customer); /** * Description Methodname:serializecustomer: Serialization of Customer objects * @author XUDP * @th Rows FileNotFoundException * @throws IOException/Serializecustomer () throws FILENOTF Oundexception, IOException {Customer customer = new Customer ("GaCl");//ObjectOutputStream object loss Out stream ObjectOutputStream oo = new ObjectOutputStream (New FileOutputStream new File ("E:/customer.txt "));
Oo.writeobject (customer); System.out.println ("Customer object Serialization success!")
");
Oo.close (); /** Methodname:deserializecustomer Description: Anti-Sequence Customer Object * * @author XUDP 40 * @ return * @throws Exception @throws ioexception private static Customer Deserializecustomer () thro WS Exception, IOException {objectinputstream ois = new ObjectInputStream (new FileInputStream-New File (
"E:/customer.txt"));
Customer customer = (customer) ois.readobject (); System.out.println ("Customer object deserialization succeeded!")
");
return to Customer; /** * <p>ClassName:Customer<p> <p>description:customer implements the serializable interface, which can be  Serialization <p> @author XUDP * @version 1.0 V * @createTime 2014-6-9 afternoon 04:20:17 class Customer implements The Serializable {//customer class does not have a definition of serialversionuid-private String name; \ private int age;Omer (String name, int age) {$ this.name = name; this.age = age;}/* * @MethodName Tostrin G-@Description rewrite the ToString () method of the Object class @author xudp @return String * @see Java.lang.object#tostri
 Ng () () * * * * @Override public String toString () {"Name=" + name + ", age=" + Age; 80} 81}

Run Result:

Both serialization and deserialization succeeded.

Let's revise the customer class to add one more sex attribute, as follows:

 The 1 class Customer implements Serializable {
 2   //customer class has no serialversionuid
 3   private String name defined;
 4   private int age;
 5 
 6   //Newly Added sex property
 7   private String sex;
 8   
 9 Public   Customer (String name, int age) {     this.name = name;
One     this.age = age;   the public   Customer (String name, int age,string sex) {     this.name = name;     this.age = age;     this.sex = sex;   @Description *
*   @MethodName toString   * To override the ToString () method of the object class   @author
xudp   * @return string   * @see Java.lang.object#tostring ()   @Override public   String toString () {     "Name=" + name + ", age=" + age;   }
31}

Then the deserialization operation is performed, and the following exception information is thrown:

1 Exception in thread "main" Java.io.InvalidClassException:Customer; 
2 Local class incompatible: 
3 stream Classdesc serialversionuid = -88175599799432325, 
4 local class Serialversion UID =-5182532647273106745

This means that the class in the file stream and class in Classpath, which is the modified class, is incompatible, is in security consideration, the program throws an error, and refuses to load. So what if we really need to add a field or method after serialization? What should I do? That is to specify the serialversionuid yourself. In the Testserialversionuid example, the Serialversionuid of the customer class is not specified, so the Java compiler will automatically give this Class A digest algorithm, similar to the fingerprint algorithm, as long as the file more than one space, The resulting UID will be completely different, and it can be guaranteed that the number is unique in so many classes. So, after adding a field, the compiler generates a UID for us because it does not explicitly specify Serialversionuid, which is certainly not the same as the one previously saved in the file, so there are 2 errors that are inconsistent with the serialized version number. Therefore, as long as we specify the Serialversionuid, we can add a field after serialization, or method, without affecting the later restore, the restored object can be used, but also a lot of methods or properties can be used.

The following continues to modify the customer class, assigning a serialversionuid to the customer, with the modified code as follows:

Class Customer implements Serializable {
  /**
   * SERIALVERSIONUID (serialized version number) defined in the Customer class *
   *
  Private Static final Long serialversionuid = -5182532647273106745l;
  private String name;
  private int age;

  The newly added sex property
  //private String sex;
  
  Public Customer (String name, int age) {
    this.name = name;
    This.age = age;
  }
  
  /*public Customer (String name, int age,string sex) {
    this.name = name;
    This.age = age;
    This.sex = sex;
  } *

  *
   * @MethodName ToString
   * @Description rewrite the ToString () method of the object class
   * @author xudp
   * @return String
   * @see java.lang.object#tostring () */
  @Override public
  string toString () {return
    " Name= "+ name +", age= "+ Age;
  }
}"

Re-perform the serialization operation, serialize the customer object to the Customer.txt file store on the local hard disk, and then modify the customer class, add the Sex property, and modify the customer Class code as follows:

Class Customer implements Serializable {
  /**
   * SERIALVERSIONUID (serialized version number) defined in the Customer class *
   *
  Private Static final Long serialversionuid = -5182532647273106745l;
  private String name;
  private int age;

  The newly added sex property
  private String sex;
  
  Public Customer (String name, int age) {
    this.name = name;
    This.age = age;
  }
  
  Public Customer (String name, int age,string sex) {
    this.name = name;
    This.age = age;
    This.sex = sex;
  }

  *
   * @MethodName ToString
   * @Description rewrite the ToString () method of the object class
   * @author xudp
   * @return string
   * @see java.lang.object#tostring () */
  @Override public
  String toString () {return
    "name=" + Name + ", age=" + Age;
  }
}

To perform the deserialization operation, this time the reverse sequence is successful, as follows:

  

Iv. Value of Serialversionuid

The Serialversionuid value is generated automatically by the Java Runtime Environment based on the internal details of the class. If you modify the source code for the class, and then recompile, the value of the serialversionuid of the newly generated class file may change.

The default value of a class's serialversionuid is entirely dependent on the implementation of the Java compiler, and for the same class, compiling with a different Java compiler may lead to different serialversionuid, and possibly the same. In order to improve the independence and certainty of serialversionuid, it is strongly recommended that the definition shown in a serializable class be serialversionuid, giving it a definite value.

There are two uses for explicitly defining SERIALVERSIONUID:

   1, in some cases, you want different versions of the class to be compatible with serialization, so you need to ensure that different versions of the class have the same serialversionuid;
2, in some cases, you do not want different versions of the class to be compatible with serialization, so you need to ensure that different versions of the class have different serialversionuid.

Thank you for reading, I hope to help you, thank you for your support for this site!

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.