Reputation: 207830
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
Reputation: 24472
Take a look at item 54, 55, 56 and 57 of the Effective Java (Joshua Bloch) that talks about Serialization. To summarize
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
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