SerialVersionUID Guide 📖 #246
pwgit-create
announced in
Learning Materials
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
The
serialVersionUIDis a unique identifier that helps with version control of serialized objects in Java. Whenan object is serialized, it generates a unique identifier based on various factors such as class name, interfaces
implemented, methods, etc. This identifier is stored along with the serialized data.
If you change the class definition (e.g., adding or removing fields, methods) and attempt to deserialize an old
version of the serialized object using the new class definition, Java will compare the
serialVersionUIDof bothversions:
serialVersionUIDs match, Java assumes that the class definitions are compatible,and deserialization proceeds smoothly.
InvalidClassExceptionis thrown.By explicitly declaring a
serialVersionUID, you ensure consistent behavior across different versions of yourclass:
the class structure that would require special handling.
Let's look at an example to illustrate this:
Suppose you have a class with version 1:
Now, if you make a minor update (e.g., adding a comment) without changing the
serialVersionUID,serialization/deserialization will still work as expected:
If, however, you add or remove significant parts of the class (e.g., a new field) without updating the
serialVersionUID, deserialization might fail because the default-generated ID has changed:In this case, if you're careful with your
serialVersionUID, you can decide whether old serialized objects arestill compatible or should throw an exception.
Beta Was this translation helpful? Give feedback.
All reactions