Java Reference
In-Depth Information
before there were inner classes, or enumerations, or a number of other features in the language
that made the names of the methods and members vary from compiler to compiler.
The problem now is that if you let the Java runtime generate your serialVersionUID , the
system will detect differences that aren't really there. This is the right failure mode, as it means
that things will not be deserialized rather than being deserialized incorrectly. But you will still
get an error that can't be explained by looking at the code, which is always something of a
puzzle.
So you are much better off taking charge of the serialVersionUID yourself. If you assign
it, you are also taking on the responsibility of changing it if you change the contents of your
class. And this will only get you started on the very hard problem of trying to deal with differ-
ent versions of classes as things change over time. But it will help.
It is important to realize that object serialization creates a copy of the graph of objects rooted
at the object being serialized. It will do the best job it can of recreating that graph, keeping
track of objects that have been put into the stream and putting references to that object only
if the same object appears again. But object serialization can't perform miracles. If you separ-
ately serialize two objects, each of which references a common third object, when you deseri-
alize the original two objects, you will get two copies of the object formerly referenced by
both. Object serialization can't know what you are going to do in the future, and doesn't keep
track of what you have done in the past (beyond the current graph of objects being serialized
or deserialized).
One other thing to keep in mind concerning object serialization has to do with the way it treats
static members of your class. These members are really part of the class of an object rather
than the object, and so it doesn't seem to make sense to send them to a different address space
as part of the serialize/deserialize operation. So all static members are implicitly treated as
transient by serialization.
There is a lot more that can be done with object serialization, including writing your own cus-
tom mechanisms for a class by using the methods readResolve() and writeReplace() . But
such specialized techniques are beyond the scope of this topic. Further, they are not the kind
of thing that makes object serialization one of the good parts of Java. What really earns the
system entry into that group of features is the way it ties the portable code of Java into a sys-
tem that allows you to transport objects, with their code, over space and time.
Search WWH ::




Custom Search