...
This noncompliant snippet implements a GameWeapon
class with a serializable field called noofWeapons
noOfWeapons
, and uses the default serialization form. Any changes to the internal representation of the class can break the existing serialized form.
Code Block | ||
---|---|---|
| ||
class GameWeapon implements Serializable { int noofWeaponsnoOfWeapons = 10; public String toString() { return String.valueOf(noofWeaponsnoOfWeapons); } } |
Compliant Solution
Ideally, implement Serializable
only when the class is not expected to evolve frequently. One way to maintain the original serialized form, at the same time allowing the class to evolve is to use custom serialization with the help of serialPersistentFields
. The static
and transient
fields allow you to specify what should not be serialized whereas the serialPersistentFields
field specifies what should be serialized. It also relieves the class from defining the serializable field within the class implementation, decoupling the current implementation from the logic. New fields can easily be added without breaking compatibility across releases.
...