Serialization grab bag

Answers to reader questions about serialization

JavaWorld readers have responded to the past three months of JavaBeans columns with some interesting questions. This month, we'll go through a grab bag of serialization topics in response to these questions. We'll look into the details of initializing transient fields when a JavaBean (or any other object) is deserialized. We'll also revisit the writeObject() and readObject() methods, and look at a new example of how they may be used. And, we'll take a look at another feature of the Java Object Serialization Specification, object validation, which checks an object after deserialization to ensure that it's valid.

Deserialization and static initialization of transients

This month I received the following reader comment:

... transient initializers aren't instantiated during object deserialization; that is, if you have: transient int fred = 4;, you would expect that this value would not be serialized during the saving process (it doesn't) but that when deserializing, it would assume a default value of 4. However, it doesn't. It assumes a value of 0 because that's the default value for things of type int. I have found that the sensible solution to this plan is:

  1. Don't have any initializers in the class definition
  2. Have a method called init(), which sets up the default values
  3. Invoke init() after the constructor has been called

However, I have had a number of problems with this depending on how the invocation of the constructor has been called, and vice versa.

I would be interested to hear if you have any other ways of achieving this.

1 2 Page 1
Page 1 of 2