Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

The easiest is to simply declare a value. Something like:

private static final long serialVersionUID = 1L;

The reason to do this is to control serialization/deserialization of your objects. If you serialize an instance of a class that does not have a serialVersionUID, the system generates one from the current class definition. If you change the class in any significant way, the system-generated id will change. This, in turn, will prevent you from deserializing an object serialized with the old id.

If you're serializing objects but not persisting them, then defining an ID is probably unnecessary (except to get rid of the compiler warning).

See this thread for more info.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top