Pentium10
Pentium10

Reputation: 207830

How to customize serialization of a complex object?

I have a complex object, with fields and reference to database that I would like to pass as serialized object. I implemented the interface, but on the other hand it doesn't work out, and get unexpected errors.

What I would like to do, is before serialization to tell that only the ID is serialized, and after on deserialization to get back the ID and reconstruct the item more easily.

In order to help for a code, I have

setId();
getId();
and Load() methods

I would like to be done inside by Object.

How can this be done?

Upvotes: 2

Views: 2710

Answers (2)

naikus
naikus

Reputation: 24472

Take a look at item 54, 55, 56 and 57 of the Effective Java (Joshua Bloch) that talks about Serialization. To summarize

  1. Don't use it until you absolutely have to.
  2. Have a serialVersionUID for your class. (please don't keep it as 1)
  3. Provide readObject, writeObject carefully
  4. Don't forget to call defaultReadObject and defaultWriteObject in the above two
  5. Mark all fields not serializable as transient
  6. Mark all fields transient that can be constructed with other fields
  7. Consider using a custom serialized form (item 55 Effective Java) if you have Linked Lists, etc.
  8. Take care if you class is a Singleton. Provide a readResolve method

And lastly, thoroughly read the javadoc for Serializable, and the Effective Java's item 54-57. It will answer your other question too.

Cheers

Upvotes: 2

krock
krock

Reputation: 29619

It is meaningless to serialize a database resourse so you will want to set your non serializable fields as transient and then resolve them in the readObject method. e.g.:

private int id;
private transient java.sql.Connection connection;

private void readObject(ObjectOutputStream out) throws IOException {
    out.defaultReadObject();
    connection = DriverManager.getConnection();
}

Here the id field will be deserialized in the defaultReadObject(), but if you want a database resource you will have to manage that yourself as transient data such as this cannot be transferred between JVMs.

Upvotes: 4

Related Questions