Java Reference
In-Depth Information
os
.
writeObject
(
theGraph
);
os
.
close
();
}
public
public
void
throws
IOException
,
ClassNotFoundException
{
ObjectInputStream is
=
new
void
dump
()
throws
new
ObjectInputStream
(
new
FileInputStream
(
FILENAME
));
System
.
out
.
println
(
is
.
readObject
());
is
.
close
();
new
}
}
See Also
For more on the standard Serialization, see the chapter on this topic in
Effective Java
.
Preventing ClassCastExceptions with SerialVersionUID
Problem
Your classes were recompiled, and you're getting
ClassCastException
s that you shouldn't.
Solution
Run
serialver
to generate a “serial version UUID” and paste its output into your classes
before you start. Or use your IDE's tools for this purpose.
Discussion
When a class is undergoing a period of evolution—particularly a class being used in a net-
working context such as RMI or servlets—it may be useful to provide a
serialVersionUID
value in this class. This is a
long
that is basically a hash of the methods and fields in the
class. Both the object serialization API (see
Saving and Restoring Java Objects
)
and the
JVM, when asked to cast one object to another (common when using collections, as in
destination do not match, a
ClassCastException
is thrown. Most of the time, this is the cor-
rect thing for Java to do.