the java language benefited adding enums it; unfortunately don't work when sending serialized objects between systems have different code levels.
example: assume have 2 systems , b. both start of same code levels, @ point start see code updates @ different points in time. assume there
public enum whatever { first; }
and there other objects keep references constants of enum. objects serialized , sent b or vice versa. consider b has newer version of whatever
public enum whatever { first; second }
then:
class somethingelse implements serializable { ... private final whatever thewhatever; somethingelse(whatever thewhatever) { this.thewhatever = thewhatever; ..
gets instantiated ...
somethingelse somethin = new somethingelse(whatever.second)
and serialized , sent on (for example result of rmi call). bad, because there error during deserialization on a: knows whatever enum class, in version doesn't have second.
we figured hard way; , anxious use enums situations "perfect enums"; because know can't extend existing enum later on.
now wondering: there (good) strategies avoid such compatibility issues enums? or have go "pre-enum" times; , don't use enums, have rely on solution use plain strings on place?
update: please note using serialversionuid doesn't here @ all. thing helps in making incompatible change "more obvious". point is: don't care why deserialization fails - because have avoid happen. , not in position change way serialize our objects. doing rmi; , serializing binary; have no means change that.
as @jesper mentioned in comments, recommend json inter-service communication. allow have more control on how unknown enum values handled.
for example, using awesome jackson can use deserialization features read_unknown_enum_values_as_null
or read_unknown_enum_values_using_default_value
. both allow application logic handle unknown enum values see fit.
example (straight jackson doc)
enum myenum { a, b, @jsonenumdefaultvalue unknown } ... final objectmapper mapper = new objectmapper(); mapper.enable(deserializationfeature.read_unknown_enum_values_using_default_value); myenum value = mapper.readvalue("\"foo\"", myenum.class); assertsame(myenum.unknown, value);
Comments
Post a Comment