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
The Serializable interface must be implemented by the class whose object needs to be persisted. The String class and all the wrapper classes implement the java. io. Serializable interface by default.
Serialization in Java allows us to convert an Object to stream that we can send over the network or save it as file or store in DB for later usage. Deserialization is the process of converting Object stream to actual Java Object to be used in our program.
Classes that are eligible for serialization need to implement a special marker interface, Serializable. Both ObjectInputStream and ObjectOutputStream are high level classes that extend java. io. InputStream and java.
The ObjectOutputStream class contains writeObject() method for serializing an Object. The ObjectInputStream class contains readObject() method for deserializing an object.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With