views:

186

answers:

5

I try to serialize an object that contains an other object which is itself serializable.

Is there a way to make it work ? The pointer to the other object seems to be lost when I serialize the first object.

+1  A: 

It should work just fine, so long as everything's serializable. What do you mean by the pointer (by which I assume you mean reference) being "lost"?

Could you provide a short but complete program which demonstrates the problem? Admittedly Java binary serialization can be fiddly at times, but this much should work fine out of the box.

Jon Skeet
+2  A: 

The "pointer" is lost indeed. After deserialization new objects are constructed.

Before you provide your code - check whether your 2nd object isn't defined as transient - this stops java serialization.

Bozho
+1  A: 

All of the attributes of the Serializable object should be serialized as well, unless they're defined as transient.

Kaleb Brasee
A: 

You might be happy using SOJO. It serializes the entire hierarchy of a Java object pretty easily.

altCognito
+3  A: 

Here are two rules concerning persistent objects:

  • Rule #1: The object to be persisted must implement the Serializable interface or inherit that implementation from its object hierarchy
  • Rule #2: The object to be persisted must mark all nonserializable fields transient

Check the article "Discover the secrets of the Java Serialization API". It's include source code and a good explanation of the serialization process.

Source code answering "How do I serialize a tree of objects?" is also available at http://java.sun.com/javase/technologies/core/basic/serializationFAQ.jsp#tree

Check also Sun's Serialization FAQ.

To know some "under the hood" details check this excellent article: The Java serialization algorithm revealed.

JuanZe