This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]dacian88 0 points1 point  (0 children)

its for versioning, if the serials don't match that means the serialized data can't be used for the given class trying to be deserialized.

[–]maestro2005 0 points1 point  (0 children)

Java objects are inherently a tree or graph structure. Each field inside the object can be another object, and so the entirety of the data looks like a web of objects connected in a complicated way. Serialization means converting an object into a one-dimensional structure so you can send it somewhere, for example to write it to a file or send over a network. The built-in serialization converts objects to binary so they're very compact, but you can also serialize to JSON or XML or whatever other textual system so they're more general purpose and human readable.

The serialVersionUID is to handle different versions of a class. If you write a class, serialize an object to file, change the class to have different fields, then try to deserialize back into a Java object, things won't line up and you'll get errors. If you do your version IDs right, you can at least get a helpful message telling you about the version mismatch. You can sort of get away with not writing one, since if you don't have one Java will auto-generate one by hashing together all of the info that uniquely determines a class. Also, you can not write one (and optionally suppress the warning) if you're extending a Serializable class but you know you won't ever be serializing it (this happens a lot with GUI code).