Java Reference
In-Depth Information
tains objects within objects, and even perhaps contains cross-referenced objects, the
Serialization framework will resolve those objects, and store only one copy of any ob-
ject. Each property then gets translated to a byte[] representation. The format of the
byte array includes the actual class name (for example:
com.somewhere.over.the.rainbow.preferences.UserPreferences ),
followed by the encoding of the properties (which in turn may encode another object
class, with its properties, etc., etc., ad infinitum ).
For the curious, if you look at the file generated (even in a text editor), you can see
the class name as almost the first part of the file.
Note Serialization is very brittle. By default, the Serialization framework generates a
Stream Unique Identifier (SUID) that captures information about what fields are presen-
ted in the class, what kind they are (public/protected), and what is transient, among oth-
er things. Even a perceived slight modification of the class (for example, changing an
int to a long property) will generate a new SUID. A class that has been saved with a
prior SUID cannot be deserialized on the new SUID. This is done to protect the serializ-
ation/deserialization mechanism, while also protecting the designers.
You can actually tell the Java class to use a specific SUID. This will allow you to serial-
ize classes, modify them, and then deserialize the original classes while implementing
some backward compatibility. The danger you run into is that the deserialization must
be backward-compatible. Renaming or removing fields will generate an exception as the
class is being deserialized. If you are specifying your own serial Serializable on your
Serializable class, be sure to have some unit tests for backward-compatibility every time
you change the class. In general, the changes that can be made on a class to keep it
backward-compatible are found here: http://docs.oracle.com/javase/7/
docs/platform/serialization/spec/serial-arch.html .
Due to the nature of serialization, don't expect constructors to be called when an object
is deserialized. If you have initialization code in constructors that is required for your
object to function properly, you may need to refactor the code out of the constructor to
allow proper execution after construction. The reason is that in the deserialization pro-
cess, the deserialized objects are “restored” internally (not created) and don't invoke
constructors.
Search WWH ::




Custom Search