@ Reprinted from :http://www.cnblogs.com/guanghuiqq/archive/2012/07/18/2597036.html

Simply speaking ,Java The serialization mechanism of is to judge the class at run time serialVersionUID To verify version consistency . When deserializing ,JVM Will transfer the serialVersionUID Local counterpart ( class ) Of serialVersionUID Compare , If they are the same, they are considered to be the same , Can be deserialized , Otherwise, the serialization version will be inconsistent .( Throw out InvalidCastException abnormal )

serialVersionUID There are two ways to generate displays :

1. One is the default 1L, such as :private static final long serialVersionUID = 1L;

2. One is based on the class name 、 The interface name 、 Member methods and properties to generate a 64 Bit hash field , such as :private static final long serialVersionUID = xxxxL;

When you implement a class Serializable Interface , If there is no definition for display serialVersionUID,Eclipse Will provide prompt function to tell you to define . stay Eclipse Click in the class warning Let's see the icon of ,Eclipse will Automatically give two ways to generate . If you don't want to define it , stay Eclipse Also in the settings of You can turn it off .

Set as follows : Window ==> Preferences ==> Java ==> Compiler ==> Error/Warnings ==> Potential programming problems take Serializable class without serialVersionUID Of warning Change to ignore that will do .

When implementing java.io.Serializable The entity of the interface ( class ) There is no explicit definition of a name serialVersionUID, The type is long Of variables ,Java The serialization mechanism will be based on the compiled class( It passes the class name , Method name and many other factors are calculated , Theoretically, it is a one-to-one mapping relationship , It's the only one ) Automatically generate a serialVersionUID The sequenced version is used for comparison , In this case , If class file ( Class name , Methodologically ) Nothing has changed ( Add space , Line break , Add notes , wait ), Even if you compile it many times ,serialVersionUID And it won't change , But once the source java There's been a slight change in the file , Generated after recompilation class In file , Its serialVersionUID It will change , This will cause deserialization to fail . If we don't want to force software versions by compiling , That is, the entity implementing the serialization interface can be compatible with the previous version , Unchanged class , You need to explicitly define a name called serialVersionUID, The type is long The variable of , The serialization entities that do not modify the value of this variable can be serialized and deserialized with each other .

If you don't think about compatibility , Just turn it off , But it's good to have this function , As long as any category implements Serializable This interface , If you don't join serialVersionUID,Eclipse I'll give it to you warning Tips , This serialVersionUID To make the category Serializable Backward compatibility .

Question 1 : Suppose there is A End sum B End , If 2 Situated serialVersionUID atypism , What's wrong with it ?

Question two : hypothesis 2 It's about serialVersionUID Agreement , If A Add a field to the end ,B The end is the same , What will happen ?

Question 3 : hypothesis 2 It's about serialVersionUID Agreement , If B Add a field to the section ,A The end is the same , What will happen ?

Question 4 : hypothesis 2 It's about serialVersionUID Agreement , If A Reduce one field from the end ,B The end is the same , What will happen ?

Question five : hypothesis 2 It's about serialVersionUID Agreement , If B Reduce one field from the end ,A The end is the same , What will happen ?

Examples are as follows : Write 2 Classes , Same class name , The fields are the same , In the same way . In different bags , To imitate A End sum B End .

Entity class : In this case , Testing class SerialTest The former executive representative A End , then , Testing class DeserialTest The former executive representative B End .

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;
}
}

Test class , representative A End serialization

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 , representative B Deserialization of the end

package com.test.serializable;
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream;
public class DeserialTest
{
public static void main(String[] args)
{
Serial serial2;
try
{
FileInputStream fis = new FileInputStream(“H://serialTest.txt”);
ObjectInputStream ois = new ObjectInputStream(fis);
serial2 = (Serial) ois.readObject();
ois.close();
System.out.println(“Object Deserial” + serial2);
System.out.println(“B also is OK!”);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}

Question 1 : Suppose there is A End sum B End , If 2 Situated serialVersionUID atypism , What's wrong with it ?

The answer is as follows :

1) Execute the test class first SerialTest, And then modify serialVersion value ( Or comment it out serialVersion And compile ), Then execute the test class DeserialTest, Report errors :

java.io.InvalidClassException: com.test.serializable.Serial; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 11

2)A End sum B I don't even show it serialVersionUID, The entity class has not changed ( If class file ( Class name , Methodologically ) Nothing has changed ( Add space , Line break , Add notes , wait ),). serialize , Deserialization ok .

Question two : hypothesis 2 It's about serialVersionUID Agreement , If A Add a field to the end ,B The end is the same , What will happen ?

Answer two : serialize , Deserialization ok ,A The field added by the end is missing ( By B End ignore ).

Question five : hypothesis 2 It's about serialVersionUID Agreement , If B Reduce one field from the end ,A The end is the same , What will happen ?

answer : Similar to question two , serialize , Deserialization ok ,B End field less than A End ,A The field value of the end is missing ( By B End ignore ).

Question 3 : hypothesis 2 It's about serialVersionUID Agreement , If B Add a field to the section ,A The end is the same , What will happen ?

Question 4 : hypothesis 2 It's about serialVersionUID Agreement , If A Reduce one field from the end ,B The end is the same , What will happen ?( Similar to question three , Four answers : serialize , Deserialization ok ,B The end field is redundant A End ,B The extra fields are given the default values of the corresponding types )

Answer three : serialize , Deserialization ok ,B The new added int Fields are given default values 0.

Examples are as follows :

3) Execute first SerialTest, Then add a field to the entity class age, Then execute the test class DeserialTest.

package com.test.serializable;
import java.io.Serializable;
public class Serial implements Serializable
{
private static final long serialVersionUID = -2337937881709830076L; //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 ;// stay B Add a new field to the end
}

Modify the test class accordingly DeserialTest, Print out 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 serial2 ;
try
{
FileInputStream fis = new FileInputStream(“serialTest.txt”);
ObjectInputStream ois = new ObjectInputStream(fis);
serial2 = (Serial)ois.readObject();
ois.close();
System.out.println(“Object Deserial”+serial2+” age=”+serial2.age);
}
catch (FileNotFoundException e)
{ // TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{ // TODO Auto-generated catch block
e.printStackTrace();
}
}
}

The results are as follows :

Object DeserialDATA: 1 song age=0

Description serialization , Deserialization ok ,B The new added int Fields are given default values 0.

The above situation is helpful to increase / Reduce Field / Method All applicable .

// But when serialVersionUID Phase at the same time , It will be different field With type Default value Deserialize, Avoid incompatibilities .

Back to directory |·( work )·)

Q:java in serialVersionUID More related articles on the role of

  1. JAVA in protected The role of

    JAVA in protected The role of   1.public:public Indicates that the data member . Member functions are open to all users , All users can call it directly 2.private:private Express private ownership , Private means ...

  2. Java in hashCode The role of

    turn  http://blog.csdn.net/fenglibing/article/details/8905007 Java in hashCode The role of 2013-05-09 13:54 64351 Human reading ...

  3. A deep understanding Java in final The role of ( One ): from final Analysis of the role of String The underlying reason for designing immutable classes

    Statement : This blog is an original blog , Without consent , Shall not be reproduced ! Guys, if you see it somewhere else , Suggest or come csdn Let's see ( The original link is http://blog.csdn.net/bettarwang/article/det ...

  4. Java in Volatile The role of

    Java in Volatile The role of Read a few blogs , I don't understand . But in a nutshell , It's in our multithreading development . We use it Volatile Keyword to define a variable or attribute , Every time a thread uses a variable . Will read the variable after the change ...

  5. java.io.Serializable in serialVersionUID The role of

    The process of converting an object into a sequence of bytes is called object serialization . The process of restoring a byte sequence to an object is called deserialization of the object . Object serialization has two main uses : 1) Permanently save the byte sequence of the object to the hard disk , Usually in a file : 2) Online ...

  6. java The construction method and its function in the process of construction

    The function of constructor is to initialize the class . If you don't define the form of any construction method , The program will take a constructor for you without any parameters , Then you can only use the method without parameters when you generate the object of the class , Such as :class a {}// There is no constructor . structure ...

  7. Java The role of the interface in

    Reproduced in :https://www.zhihu.com/question/20111251 confused : For example, I defined an interface , But I also need to write the implementation method of the interface in the class that inherits this interface , Then I might as well write the implementation method directly in this class ...

  8. Java in static The role of

    static  The role of keywords stay  Java in  static  Keywords are 4 Use scenarios , Here are the introduction : 1.static Member variables public class Student { // Static member variable pr ...

  9. java in The role of static blocks

    ( One )java Static code block The static method is different from the general case , If some code has to be executed when the project starts , You need to use static code blocks , This kind of code is active ; It needs to be initialized when the project starts , Without creating objects , Other procedures ...

Random recommendation

  1. Get into meta Mode turn off backlight

    1. Modify file : mediatek/platform/mt6582/lk/boot_mode.c 2. Modify the content : boot_mode_select() function : mt65xx_blacklight_of ...

  2. UART to Serial Terminal( Reprint )

    The previous <UART Explained> It introduces UART Basic information of , It focuses on UART The signal of . The article excerpted from this article focuses on the baud rate (Baud Rate) Related content , The higher the baud rate , The faster the transmission speed , But the actual ...

  3. from MySQL+MMM To MariaDB+Galera Cluster : A high availability system transformation

    There are few things that are more available than launching (HA) After the system, we often see the system crash worse . For us Rails For the team running the machine , This failed HA System is MySQL Multi master replication Manager (MMM). We've been looking for MMM For a while ...

  4. 【NDK Development 】 Use NDK Development android

    I learned a little today android NDK, So write it down . It is said that NDK from r7 Start bringing your own compiler , stay windows There is no need to configure cygwin Environment . Now I use NDK r10 To develop . In the morning NDK And write an example , however ...

  5. IO Stream learning summary

    Just finished today java Of io Flow operation , Take a look at the main thread , There is no guarantee that it will be handy in the future , But at least when you use it, you will know that there is such a function that can be realized , Here is a brief summary of the study : IO Streams are mainly used for hard boards . Memory . Keyboard and so on ...

  6. use Js Of eval analysis JSON Attention points in

    stay JS Lieutenant general JSON The string of is parsed into JSON data format , There are generally two ways : 1. One for use eval() function . 2. Use Function Object for return parsing . Use eval Function to parse , And use jquery Of ea ...

  7. TP Hide the entrance

    We know , stay thinkphp One of the cases of .htaccess file , It's equipped with URL Some rewriting rules of , Such as : <IfModule mod_rewrite.c>  RewriteEngine on ...

  8. S50 Contactless IC Introduction to card performance (M1)

    One . Main indicators It is divided into 16 Sectors , Each sector is 4 block , each 16 Bytes , Block as access unit : Each sector has an independent set of passwords and access control : Each card has a unique serial number , by 32 position : It has a conflict prevention mechanism , Support multi card operation : No power , It comes with an antenna , ...

  9. Spring JdbcTemplate Querying examples

    Here are few examples to show you how to use JdbcTemplate query() methods to query or extract data f ...

  10. Android kxml analysis WBXML

     WAP Binary XML Well defined XML Fragments express synchronization server Address . Remote database name . Login account and so on . Two access methods : Right now kxml Two kinds of support wap Format :WBXML/WML. And there are two ways to parse ...