I've noticed that in my company's codebase, a common pattern is to set the serialVersionUID of a class to the hash code of the class, like this:

public final class ClassName implements Serializable {

    private static final long serialVersionUID = ClassName.class.hashCode();

    [...]

}

Is this a valid approach for setting a class' serialVersionUID?

2 Answers

6
Joachim Sauer On

Class has no explicitly defined hashCode() method, so it's not defined to be stable.

That means that you can (and probably will) get different results for MyClass.class.hashCode() between different runs, even on the same JVM and definitely between different JVM implementations and/or versions.

This means that the serialized data from any one JVM will likely only be usable within that same JVM.

Now that might be used as an intentional way of avoiding the use of serialization for cross-VM communication (it's not a "security mechanism" or anything like that, but it can be used to quickly detect attempts to use serialization for cross-VM communication). But if that is the goal then flat out using a random number is probably better.

3
Eugene On

This is a horrible idea. There are multiple strategies of how a hashCode is computed (Class::hashCode is Object::hashCode). Under java-8 the default is Marsaglia-XOR-Shift, a pseudo-random generator that will get you an int; but that is subject to change from VM-to-VM and there are multiple ways to alter that from the same version too, see this answer for details.