2

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?

Richard Fearn
  • 25,073
  • 7
  • 56
  • 55
  • 2
    Well, `Class.hashCode()` actually is `Object.hashCode()` so it depends on the memory location that class resides in. That being said you probably realize that's not actually a good value to use as it would probably differ between runs. However, since the old serialization mechanism is deprecated anyway you can also just not use `serialVersionUID` anymore (or use some default value). – Thomas May 13 '19 at 09:35
  • There are plugins for IDE that help you to generate `serialVersionUID`. For example [this one](https://plugins.jetbrains.com/plugin/185-generateserialversionuid) for IntelliJ – Nikolai Shevchenko May 13 '19 at 09:37
  • @Thomas: "hashCode may *or may not* be implemented as some function of an object's memory address at some point in time.", emphasis mine. – Joachim Sauer May 13 '19 at 09:37

2 Answers2

6

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.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
3

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.

Eugene
  • 117,005
  • 15
  • 201
  • 306