Skip to main content

Home/ Java Development/ Group items tagged Serializable

Rss Feed Group items tagged

Rinav G

JavaBlogging » What is serialVersionUID? - 2 views

  • private static final long serialVersionUID = 1L
  • and it is still there even after the program finished. Let’s see if we can read that file once again, this time without creating it first.
  • Now, let’s see what happens, when we change the serialVersionUID value and try to deserialize once again our file. Change the line 2 in the class SerializeMe so that serialVersionUID contains now 2 instead of 1:
  • ...13 more annotations...
  • serialVersionUID = 2L;
  • static final
  • Exception in thread "main" java.io.InvalidClassException:
  • As you can see, this time the deserialization didn’t go well. ObjectInputStream complained about the serialVersionUID being changed.
  • How does he know that it changed? If serialVersinUID is static, then it should not have been serialized in the first place, and there should be no information about the previous value 1 during the deserialization, right? Well, serialVersionUID is an exception to the rule that “static fields don’t get serialized”.
  • Moreover, if there is no serialVersionUID officially declared in the class to be serialized, compiler automatically adds it with a value generated based on the fields declared in the class.
  • The deserialization of that object does not necessarily have to occur exactly after serialization. It can occur after a few months or on a completely different JVM
  • there is a chance that the class declaration has changed between serialization and deserialization.
  • It checks if the data read from the input stream is compatible with the current definition of the class.
  • when the visibility of a field changes, the serialVersionUID changes too.
  • sometimes you just want for some reason to forbid deserialization of old serialized objects,
  • you might tend to write it once for every serializable class ( or have it generated by the IDE ) and forget about it. WRONG !!!
  • If you write it once and don’t take care to update it when necessary, you loose all the merits of serialVersionUID.
  •  
    What is serialVersionUID? What is it Used For???
1 - 1 of 1
Showing 20 items per page