...
Code Block | ||
---|---|---|
| ||
class GameWeapon implements Serializable { int noOfWeapons = 10; public String toString() { return String.valueOf(noOfWeapons); } } |
Compliant Solution (serialVersionUID
)
In this solution, the class has a serialVersionUID
which contains a number unique to this version of the class. Any attempt to deserialize a stream with a GameWeapon
object of a different version will yield an exception.
Code Block | ||
---|---|---|
| ||
class GameWeapon implements Serializable {
private static final long serialVersionUID = 24L;
int noOfWeapons = 10;
public String toString() {
return String.valueOf(noOfWeapons);
}
}
|
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 one 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 overall logic. New fields can easily be added without breaking compatibility across releases.
...