Search code examples
javareflectionserialversionuid

why is not safe to rely on ObjectStreamClass.getSerialVersionUID?


The java spec says: "it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations"

Please could someone dig into this? The getSerialVersionUID() method does reflection, and reflection is used commonly everywhere, so what is compiler-dependent?


Solution

  • Brilliant explanation of this question is given in J. Bloch book "Effective Java":

    "Item 74: Implement Serializable judiciously":

    If you do not specify this number explicitly by declaring a static final long field named serialVersionUID, the system automatically generates it at runtime by applying a complex procedure to the class. The automatically generated value is affected by the class’s name, the names of the interfaces it implements, and all of its public and protected members. If you change any of these things in any way, for example, by adding a trivial convenience method, the automatically generated serial version UID changes

    UPD: I was also asked in commentary, why it is compiler-dependent. Actually compiler-dependency here is not about getSerialVersionUID() algorithm itself (method is invoked in runtime, sure), but it is in how class is described itself. For instance some synthetic methods can be added into the class at compile time, which will be counted in SUID as well. For details, look at method ObjectStreamClass.computeDefaultSUID(), what it does and how computes default SUID.