This article is starting in http://youngzy.com/
It's not always clear what the serialversionuid field in a Java object does.
Are there or not, are there any differences between them? Except for the yellow warning that was prompted in eclipse.
Today finally knows that the original is in object serialization this piece has effect.
Look at an example.
There is an object such as User:
1 classUserImplementsSerializable {2 3 String username;4 intAge ;5 String gender;6 Date Regday;7 BooleanMartialstatus;8 9 @OverrideTen PublicString toString () { One return"User [username=" + Username + ", age=" + Age + ", gender=" + Gender + ", regday=" +Regday A+ ", martialstatus=" + Martialstatus + "]"; - } - the}
Now serialize this object to the hard disk:
1 Public voidTestwriteobject () {2User User =NewUser ();3 4User.username = "Jack";5User.password = "1234567";6User.age = 20;7User.gender = "Male";8User.regday =NewDate ();9User.martialstatus =false;Ten One //the suffix name of the file does not affect, either txt,io, or even no suffix AObjectserialize.writeobject (User, "D:\\tmp\\obj"); -}
Note: Objectserialize is a simple tool class for object-serialized access to the author's own encapsulation.
Same below
Read the object information from the corresponding file:
1 Public void Testreadobject () {2 User user = (user) Objectserialize.readobject ("D:\\tmp\\obj"); 3 System.out.println (user); 4 }
So far, it's all normal. The ability to store objects and to read object information correctly.
If the user object adds another nationality (nationality) field, the new user class is as follows (the main difference is the new field on line 8th):
1 classUserImplementsSerializable {2 3 String username;4 intAge ;5 String gender;6 Date Regday;7 BooleanMartialstatus;8String nationality;//New Fields9 Ten @Override One PublicString toString () { A return"User [username=" + Username + ", age=" + Age + ", gender=" + Gender + ", regday=" +Regday -+ ", martialstatus=" + Martialstatus + ", nationality=" + nationality + "]"; - } the
This time again to read the original object file, you will get an exception message:
java.io.InvalidClassException: org.young.elearn.io.User; local class incompatible: stream classdesc serialVersionUID = 7967476135812239100, local class serialVersionUID = 905986497687499238
serialversionuid 's problem!!!
The serialversionuid of the user object stored in the file is inconsistent with the Serialversionuid of the current user object (User.class). Because if a Java object does not specify serialversionuid , then the System (JVM) dynamically assigns one.
To solve this problem, simply specify serialversionuid when defining the user object, i.e.:
1 class Implements Serializable {23 Private Static Final long serialversionuid = 7967476135812239100L; 4 5 // same code as before 6 7 }
Detailed code can be found in: GitHub
Read the original
Java | It turns out that Serialversionuid's usefulness is here.