Search code examples
javainheritanceinterfaceserialversionuid

Recommend declaration of a constant through an interface


I've been playing with the serializable interface for a little pet project of mine for a while, and I often notice a warning about how I should define static final long serialVersionID.

I've been searching for a way to make my own interfaces produce a similar warning (forcing/reccomending the declaration of a constant in whatever class implements it) and haven't found anything so far. The Seralizable interface is just a marker interface, so it doesn't actually contain anything and the closest I've ever came to answering my question is with this thread on dreamincode.

Can anybody help, because that sounds like a very useful feature?


Solution

  • serialVersionID (a field) is not declared as a member the Serializable interface. The field name is merely a convention and the field is accessed by reflection at runtime. It is not possible to use interfaces to define a field contract.

    The warning is "compiler magic" that knows it should emit a warning when encountering a type implementing Serializable that does not have such a field. This warning behavior cannot be emulated for other fields in application code alone - obtaining a similar warning requires using a [customized] compiler or lint/code-checker that understands the desired heuristics.