Functions of serialversionuid

Source: Internet
Author: User

To put it simply, Java's serialization mechanism verifies version consistency by judging the serialversionuid of the class at runtime. During deserialization, the JVM compares the serialversionuid In the byte stream with the serialversionuid of the corresponding local entity (class). If they are the same, they are considered to be consistent, deserialization is supported. Otherwise, the serialization version is inconsistent. (Invalidcastexception)

Serialversionuid can be generated in two ways: one is the default 1l, for example, Private Static final long serialversionuid = 1l; one is to generate a 64-bit hash field based on the class name, Interface Name, member method, and attribute, for example, Private Static final long serialversionuid = xxxxl; if a class implements the serializable interface and serialversionuid is not displayed, eclipse will provide this prompt function for you to define it. In eclipse, click the "warning" icon in the class, and eclipse will automatically generate the two methods. If you do not want to define it, you can disable it in eclipse settings as follows: window ==> preferences ==> Java ==> compiler ==> error/warnings ==> potential Programming Problems change the serializable class without serialversionuid's warning to ignore.
When Java. io. when the entity (class) of the serializable interface does not explicitly define a variable named serialversionuid whose type is long, the Java serialization mechanism will follow the compiled class (it uses the class name, method names and many other factors are computed. In theory, they are the one-to-one ing relationship, that is, the only one.) A serialversionuid is automatically generated for the serialization version. In this case, if the class file (Class Name, method description, etc.) does not change (adding spaces, line breaks, adding comments, etc.), the serialversionuid will not change even if it is compiled multiple times.

If we do not want to forcibly divide the software version by compiling, that is, the entity implementing the serialization interface can be compatible with the previous version. If the class is not changed, we need to explicitly define a class named serialversionuid, variables of the long type can be serialized or deserialized to each other without modifying the serialization entity of the variable value.

If you do not consider compatibility issues, turn it off, but this function is good. If serializable is implemented in any category, if serialversionuid is not added, eclipse will give you a warning that this serialversionuid is backward compatible for this type of serializable.

Question 1: if there are two serialversionuids that are inconsistent, what error will happen?

Question 2: Suppose that the serialversionuid at 2 is the same. If a field is added to end a and end B remains unchanged, what will happen?

Question 3: Suppose that the serialversionuid at 2 is the same. If a field is added to segment B and the side remains unchanged, what will happen?

Question 4: Suppose that the serialversionuid at 2 is the same. What will happen if the side reduces a field and the B side remains unchanged?

Question 5: Suppose that the serialversionuid at 2 is the same. What will happen if the field of B is reduced and the value of a remains unchanged?

 

Example: write two classes. The class names are the same, the fields are the same, and the methods are the same. Put them in different packages to imitate the and B ends.

Entity class: In this example, before the test class serialtest is executed, it represents end a and end B before the test class deserialtest is executed.

package com.test;import java.io.Serializable;public class Serial implements Serializable{ /****/ private static final long serialVersionUID = 6977402643848374753L; int id;String name;public Serial(int id, String name) {this.id = id;this.name = name;}public String toString() {           return "DATA: " + id + " " +name;         }   }

 

Testing class, representing serialization of end

package com.test.serializable;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;public class SerialTest {/**   * @param args   */ public static void main(String[] args) {   // TODO Auto-generated method stub   Serial serial1 = new Serial(1,"song");   System.out.println("Object Serial"+serial1);     try {    FileOutputStream fos = new FileOutputStream("serialTest.txt");    ObjectOutputStream oos = new ObjectOutputStream(fos);    oos.writeObject(serial1);    oos.flush();    oos.close();         } catch (FileNotFoundException e) {    // TODO Auto-generated catch block    e.printStackTrace();   } catch (IOException e) {    // TODO Auto-generated catch block    e.printStackTrace();   } } }

 


Test class, representing the deserialization of side B

Package com. Test. serializable;

Import java. Io. fileinputstream; import java. Io. filenotfoundexception; import java. Io. ioexception; import java. Io. objectinputstream;

Public class deserialtest {

/*** @ Param ARGs */public static void main (string [] ARGs) {// todo auto-generated method stub serial; try {fileinputstream FCM = new fileinputstream ("serialtest.txt"); objectinputstream OIS = new objectinputstream (FCM); Serial = (Serial) Ois. readobject (); ois. close (); system. out. println ("Object deserial" + Serial);} catch (filenotfoundexception e) {// todo auto-generated Catch Block E. printstacktrace ();} catch (ioexception e) {// todo auto-generated Catch Block E. printstacktrace ();} catch (classnotfoundexception e) {// todo auto-generated Catch Block E. printstacktrace ();}}

}

Question 1: if there are two serialversionuids that are inconsistent, what error will happen?

The answer is as follows:

1) first execute the test class serialtest, then modify the value of serialversion (or comment out the serialversion and compile it), and then execute the test class deserialtest. An error is returned:

Java. Io. invalidclassexception: COM. Test. serializable. Serial; local class incompatible: stream classdesc serialversionuid = 1, local class serialversionuid = 11

2) Writing serialversionuid is not displayed on both client a and client B, and the entity class is not changed (if the class file (Class Name, method description, etc.) is not changed (adding spaces or line breaks, add comments, etc ),). serialization and deserialization are normal.

 

Question 2: Suppose that the serialversionuid at 2 is the same. If a field is added to end a and end B remains unchanged, what will happen?

Answer 2: serialization and deserialization are normal, and the fields added to end a are lost (ignored by end B ).

Question 5: Suppose that the serialversionuid at 2 is the same. What will happen if the field of B is reduced and the value of a remains unchanged?

Answer: similar to question 2, serialization and deserialization are normal. The number of fields on the B side is smaller than that on the side, and the number of fields on the side is lost (ignored by the B side ).

 

Question 3: Suppose that the serialversionuid at 2 is the same. If a field is added to segment B and the side remains unchanged, what will happen?

Question 4: Suppose that the serialversionuid at 2 is the same. What will happen if the side reduces a field and the B side remains unchanged? (Similar to Question 3. Answer 4: serialization and deserialization are normal. The B-side field is redundant. The B-side field is assigned the default value of the corresponding type)

Answer 3: serialization and deserialization are normal. The new int field on the B side is assigned the default value 0.

Example:

3) execute serialtest first, add a field age to the object class, and then execute deserialtest.

Package com. Test. serializable;

Import java. Io. serializable;

Public class serial implements serializable {

/*****/Private Static final long serialversionuid =-2334737881709830076l;

/***** // Private Static final long serialversionuid = 1l; int ID;

String name; Public serial (int id, string name) {This. id = ID; this. name = Name;} Public String tostring () {return "data:" + ID + "" + name;} public int age; // Add a new field to end B}

Modify the test class deserialtest to print the age value.

Package com. Test. serializable;

Import java. Io. fileinputstream; import java. Io. filenotfoundexception; import java. Io. ioexception; import java. Io. objectinputstream;

Public class deserialtest {

/*** @ Param ARGs */public static void main (string [] ARGs) {// todo auto-generated method stub serial; try {fileinputstream FCM = new fileinputstream ("serialtest.txt"); objectinputstream OIS = new objectinputstream (FCM); Serial = (Serial) Ois. readobject (); ois. close (); system. out. println ("Object deserial" + Serial + "age =" + serial2.age);} catch (filenotfoundexception e) {// todo auto-generated Catch Block E. printstacktrace ();} catch (ioexception e) {// todo auto-generated Catch Block E. printstacktrace ();} catch (classnotfoundexception e) {// todo auto-generated Catch Block E. printstacktrace ();}}

}

The output is as follows:

Object deserialdata: 1 Song age = 0

It indicates that the serialization and deserialization are normal, and the new int field on the B side is assigned the default value 0.

 

The above conditions apply to adding/decreasing fields/methods.

// But when the serialversionuid is the same, it will deserialize different fields with the default value of type to avoid incompatibility issues.

Functions of serialversionuid

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.