Java serialization: which classes should "implement Serializable"?

so I know that maybe in the end I can figure it out, but I could not find a topic that answers this seemingly simple question.

I am serializing a vector of a set of objects, each of which has one user-defined class. I know that vectors are serializable. Should I also make the user-implemented class serializable? And each of these custom classes contains other custom classes. Do I need to designate them as a Serializable implementation? (and so on, or just a top-level class should implement Serializable)?

(Forget that you should use a list of arrays instead of lists, I've heard this before, I practice, because I hear that vectors are good for multithreading. I found topics that discuss similar things, but not quite that)

thanks

+4
source share
3 answers

Yes, you are right: everything that is serialized, including all classes referenced by fields (instance variables), must be implemented Serializable, or the field must be transient.

In your case, the user class must implement Serializableand have fields of type Serializable. This is applied recursively, so the fields of the field class should also be Serializable, etc.

transient .

+5

Serializable :

, Serializable. NotSerializableException .

, , , , Serializable, , , transient.

+1

,

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());
    }
...
+1

All Articles