squirrelsareduck
squirrelsareduck

Reputation: 884

Serialization Java: which classes need to "implement Serializable"?

so I know I could probably figure it out eventually, but I couldn't really find a topic that answers this seemingly simple question.

I am serializing a vector of a set of objects, with each such object pertaining to one user-defined class. I know vectors are serializable. Do I also have to make the user-defined class implement serializable? And, each of these user-defined classes contains other user-defined classes. Do those have to be labeled as implementing Serializable as well? (and so on, or do just the top-level class need to implement Serializable)?

(Forget noting that arrayLists should be used instead of vectors, I've heard that before, I'm practicing because I hear vectors are good for multithreading. I found topics that discuss similar stuff, but not precisely this)

Thanks

Upvotes: 7

Views: 3595

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136102

Theoretically you can implement a custom Vector with custom serialization and serialize non-serializable objects, like here

class Y {
    int y;
    Y(int y) {
        this.y = y;
    }
}

class X implements Serializable {
    transient Y y;

    private void writeObject(ObjectOutputStream os) throws IOException {
        os.defaultWriteObject();
        os.writeInt(y.y);
    }

    private void readObject(ObjectInputStream is) throws ClassNotFoundException, IOException {
        is.defaultReadObject();
        y = new Y(is.readInt());
    }
...

Upvotes: 1

Bohemian
Bohemian

Reputation: 425308

Yes, you are correct: Anything being serialized, including all classes referred to by fields (instance variables), must implement Serializable, or the field must be transient.

In your case, the user defined class must implement Serializable, and have fields whose type is Serializable. This applies recursively, so fields of the class of the fields must also be Serializable, etc.

The transient keyword tells the serialization mechanism to ignore the field for the purposes of serialization.

Upvotes: 7

Paul Bellora
Paul Bellora

Reputation: 55233

From the Serializable documentation:

When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object.

So yes, all objects referenced by the vector, directly and indirectly, will need to be Serializable, unless of course they're marked as transient.

Upvotes: 2

Related Questions