We sometimes need to serialize an object, save it locally, or send it to the network, and then reverse-sequence the object. Usually the class of this object needs to implement the serializable interface, when implementing the interface, it is generally necessary to provide a static variable, like this:
public class Throwable implements java.io.Serializable { private static final long Serialversionuid = 30426860556580 47285L;
If you define a class that implements the Serializable interface, but does not provide a serialversionuid, an IDE like eclipse usually reminds you to add that static variable and can help you generate it automatically. So what is the role of this serialversionuid?
When we serialize an object to a local and then modify a member variable of the class, or add it, can you deserialize the object successfully? If there is no serialversionuid, then naturally will be error, but if you have the SERIALVERSIONUID variable, when you modify the name of a member variable, or add a member variable, or add modified method, can be successfully deserialized, here Note that The name of the variable that was modified is actually the equivalent of a new variable name. In general, the role of Serialversionuid is to ensure the compatibility of class versions when serializing and deserializing objects,
Here is an example of what you can do to test your learning with this example.
public class Serializabledemo extends Object implements Serializable {private static final long Serialversionuid = 349697 9029493924435l;public byte B = 112;//int c = 32;public byte Getb () {return B;} public void Setb (byte b) {this.b = b;} public void Saveobject () {try {fileoutputstream fos = new FileOutputStream (New File ("E:\\demo2.txt")); O Bjectoutputstream OS = new ObjectOutputStream (FOS); Serializabledemo s = new Serializabledemo (); Os.writeobject (s); Os.flush (); Os.close ();} catch (FileNotFoundException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//Todo Au To-generated catch Blocke.printstacktrace ();}} public void ReadObject () {try {FileInputStream FIS = new FileInputStream (New File ("E:\\demo2.txt")); ObjectInputStream OIS = new ObjectInputStream (FIS); Serializabledemo s2 = (Serializabledemo) ois.readobject (); System.out.println (S2.getb ()); Ois.close ();} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}catch (ClassNotFoundException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} public static void Main (string[] args) {Serializabledemo ser = new Serializabledemo ();//Ser.saveobject (); ser.readobject ();}}
The role of Serialversionuid in Java