peterk
peterk

Reputation: 5444

Is there a way to automatically re-generate serialVersionId when class/code signature changes?

we have a whole bunch of serialized classes but want the database bits to be invalidated whenever the "signature" ie: field structure and serialization code for a class changes,

Is there a utility that can generate a "hash" for a class file that will optimally detect when the serialization structure for java.serializable changes for that class?

Upvotes: 4

Views: 288

Answers (1)

scottb
scottb

Reputation: 10084

There's really no way to "optimally detect when a serialization structure changes" for one rather important reason:

Serialization breaks encapsulation.

When you implement Serializable, all the private and package-private fields and members of a class become part of that class's exported API. From the moment that a class is published into the wild, its serialized form (which contains all of its implementation details) is a part of its contract. Changing the serialized form will have one of two consequences:

  • Backward compatibility. Because Serializable breaks encapsulation, the serialized form becomes part of its exported API. When an implementation detail changes, at the developer's discretion customized readObject() and writeObject() methods can be designed to continue to support the original serialized form (even if it would change as a result of the new implementation). This is desireable if the API is far flung and changing the serialized form would break many clients of the API. In this case, even though the serialized form would change by the new implementation, the serialVersionUID will need to remain the same to continue to support the original serialized form.

  • Forced upgrade. If the implementation of a class changes and it is impossible or infeasible to support the original serialized form, changing the serialVersionUID will cause clients of the API to break, thereby forcing clients to be upgraded to use the new serialized form. This may be desireable in certain circumstances (but will force clients to upgrade their code).

It is worth mentioning that if you do not explicitly declare a static final serialVersionUID in your serializable class, the Java environment will automatically compute one for you by applying a complex procedure to the code (that takes into account fields and method signatures).

In short, the serialVersionUID should track with the serialized form that is used rather than the actual class implementation. If you want the serialVersionUID to change automatically whenever the class implementation changes, you can simply omit the explicit declaration of the serialVersionUID (but this may have other negative consequences). The decision to change the serialVersionUID needs to be made explicitly depending on how you want your API to behave when an implementation detail changes.

Upvotes: 3

Related Questions