views:

48

answers:

2

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?

+4  A: 

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.

krock
Would you be kind to help me out with an example for a couple of fields. It's my very first task doing serialization.
Pentium10
Just have a look at the JavaDoc of `Serializable`.
musiKk
Another question. I have a 3 level inheritance, abstract->first imp->second implementation. The 2nd is serializable only, but the database is defined in abstract. Do I have to flag all fields as transient in the abstract and first level implementation too?
Pentium10
@Pentium10 as the abstract class is not serializable, nothing in it will be serialized/deserialized. the default constructor will be called for the abstract class on deserialization.
krock
A: 

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

naikus