It has baffled me from the launch of the Serializable
interface why I have to incorporate this field in all of my classes. I understand that this interface needs a unique identifier to mark the class but why cant they generate this at run-time. For instance they could generate it using an MD5 hash of the fully-qualified class name or a similar methodology used to handle duplicates in their rare occurrence (Which is, I'm sure, what eclipse does when asked to generate the id anyway).
So what I'm asking (no this post isn't just a rant against the standard library) is exactly how the serialization field is used by the framework?
The reason I would like to know because I am going to try to create an Aspect (in AspectJ or other language) that will add the serialVersionUID field using an MD5 hash and is able to handle collisions in a way that is acceptable to the API.
I will post the results if I can get it working.
There is no requirement to have the serialVersionUID
field. If you don't provide one, Java will generate one based on the fields and methods of your class.
The reason why you might want to specify serialVersionUID
is to prevent the value from changing when methods are changed, which doesn't impact the serialized binary. Consider the class:
public class Person implements Serializable {
private String name;
public String getName() {
return name;
}
}
No serialVersionUID
was specified. If you run serialver Person
it returns:
Person: static final long serialVersionUID = 3793453319058452486L;
Now you decide to add a method but leave the fields the same.
public class Person implements Serializable {
private String name;
public String getName() {
return name;
}
public Object foo() {
return "bar";
}
}
The serialized binary is still fully compatible with the old version, but the serialVersionUID
is different:
Person: static final long serialVersionUID = -6188734029437600310L;
With a different serialVersionUID
, deserializing will result in a serialVersionUID mismatch error. The workaround is declare your own serialVersionUID
by setting it to any value (I set it 1L
), and changing it whenever the fields have changed.
Also see this related question "What is a serialVersionUID and why should I use it?" for a more detailed discussion.