...
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.
Code Block | ||
---|---|---|
| ||
class WeaponStore implements Serializable { int noOfWeapons = 10; // Total number of weapons } public class GameWeapon implements Serializable { WeaponStore ws = new WeaponStore(); private static final ObjectStreamField[] serialPersistentFields = {new ObjectStreamField("ws", WeaponStore.class)}; private void readObject(ObjectInputStream ois) throws IOException { try { ObjectInputStream.GetField gf = ois.readFields(); this.ws = (WeaponStore) gf.get("ws", ws); } catch (ClassNotFoundException e) { /* Forward to handler */ } } private void writeObject(ObjectOutputStream oos) throws IOException { ObjectOutputStream.PutField pf = oos.putFields(); pf.put("ws", ws); oos.writeFields(); } public String toString() { return String.valueOf(ws); } } |
Exceptions
Wiki Markup |
---|
Notably, according*EX1*: According to the Serialization Specification \[[Sun 06|AA. Java References#Sun 06]\], section 1.5 "Defining Serializable Fields for a Class": |
Inner classes can only contain
final static
fields that are initialized to constants or expressions built up from constants. Consequently, it is not possible to setserialPersistentFields
for an inner class (though it is possible to set it forstatic
member classes).
Finally, serialization is easy to get wrong and must consequently be carefully designedimplemented.
Risk Assessment
Failure to provide a consistent serialization mechanism across releases can limit the extensibility of classes. If classes are extended, it is possible for compatibility issues to get introducedmay result.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
SER00- J | low | probable | high | P2 | L3 |
...