Java Reference
In-Depth Information
However, sometimes you may want to allow a class to evolve in a compatible way, but you
can't immediately replace all instances in circulation. You must be willing to write code to
account for the additional fields being discarded if restoring from the longer format to the
shorter and having the default value (null for objects, 0 for numbers, and false for Boolean) if
you're restoring from the shorter format to the longer. If you are only adding fields and meth-
ods in a reasonably compatible way, you can control the compatibility by providing a long
int
named
serialVersionUID
. The initial value should be obtained from a JDK tool called
serialver
, which takes just the class name. Consider a simple class called
Serializ-
ableUser
:
public
public class
class
SerializableUser
SerializableUser
implements
implements
java
.
io
.
Serializable
{
public
public
String name
;
public
public
String address
;
public
public
String country
;
public
public
String phoneNum
;
// other fields, and methods, here...
static
static final
final
long
long
serialVersionUID
= -
7978489268769667877L
;
}
I first compiled it with two different compilers to ensure that the value is a product of the
class structure, not of some minor differences in class file format that different compilers
might emit:
$
javac SerializableUser.java
$
serialver SerializableUser
SerializableUser: static final long serialVersionUID = -7978489268769667877L;
$
jikes +E SerializableUser.java
$
serialver SerializableUser
SerializableUser: static final long serialVersionUID = -7978489268769667877L;
Sure enough, the class file from both compilers has the same hash. Now let's change the file.
I go in with an editor and add a new field,
phoneNum
, right after
country
:
public String country;
public String phoneNum;
// Added this line.
$
javac SerializableUser.java