AbhishekAsh AbhishekAsh - 9 months ago 31
Java Question

Why serialVersionUID is not enforced by Java

serialVersionUID seems to me to have a very loose specification. Any body developing a class with serializable interface can burn his hands with InvalidClassException. Also, i saw a fellow dev using int as a datatype rather than long.

So, my question why the Java designers and developers did not do something more concrete like whenever we implement serializable we have to implement a method setting serialVersionUID like the hashcode method.

So, what am i missing ? Does not seem like a double edged sword to me.

Update 1:

My bad i gave a wrong example comparing a class level thing with a instance level thing.I have seen many production issues across different companies because of this. But my general idea was cant it be made more strict by compiler in any way.

Answer Source

Keep in mind the requirements:

  • the bytes making up the ID must be present within the stream of bytes representing a serialized object
  • unless you invent something "on top", the only way to get there is by using a field
  • the ID must be identical for all objects of a class, thus the source of the ID should be static

Now step back:

  • there is no polymorphism for static methods
  • in that sense, it doesn't make a difference if you use a static field or call a static method to acquire the ID bytes when serializing an object
  • but you are going to write those bytes into the stream anyway

Conclusion: using a static field addresses all the above points . When you would be using a method - you still have to create that field. Let that sink in: when using a method, the implementation must call the method, write that as field into the byte stream - and when reading the byte stream, that number needs to be consumed - as it can't be mapped to a "real" field in the class. Compare that to: there is a static field that gets written into the byte stream and read from there.

So - from a technical point of view, the natural way to integrate such in ID somehow is by asking for a static field on the class.

Of course you could have invented something else. Modern day java might have used annotations. But such usage of annotations wasn't around when Java was invented (and this kind of serialization is in Java since day 1). And then: modern day java doesn't use "byte stream" oriented serialization in the first place.

Or as the answer from Stephen suggest - you could compute that ID based on the current content of the class. But again: this technology was invented 20 years ago. Back then, computing the id might have cost you 1, 5, 10 seconds. Compare that to the efforts of reading a static field.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download