Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added serialVersionUID CS

...

Code Block
bgColor#FFcccc
class GameWeapon implements Serializable {
  int noOfWeapons = 10;
	    
  public String toString() {
    return String.valueOf(noOfWeapons);
  }
}

Because this class does not provide a serialVersionUID, the JVM assigns it one using implementation-defined methods. If the class definition changes, the serialVersionUID is also likely to change, and the JVM will refuse to associate the serialized form of an object with the class definition if the version IDs are different.

Compliant Solution (serialVersionUID)

In this solution, the class has a an explicit 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 exceptionThe JVM will make a good-faith effort to deserialize any serialized object with the same class name and version ID.

Code Block
bgColor#ccccff
class GameWeapon implements Serializable {
  private static final long serialVersionUID = 24L;

  int noOfWeapons = 10;
	    
  public String toString() {
    return String.valueOf(noOfWeapons);
  }
}

Compliant Solution (serialPersistentFields)

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.

...