When I have Serializable
in a class, do I need to add Serializable
to all my objects within the class?
For example,
public class User implements Serializable{
private List<Role> role;
private Task task;
}
Do I need to add Serializable
to Role
and Task
, too?
public class Task implements Serializable{
// ...
}
public class Role implements Serializable{
// ...
}
Yes, you do; if your classes Task
and Role
are not Serializable
, you'll get a java.io.NotSerializableException
if you try to serialize an instance of User
.
Ofcourse, if Task
or Role
contain other non-primitive, non-transient fields, they would have to be Serializable
too, etc.
That is the simplest option.
The other option is to make those fields tranisent and "override" writeObject and readObject to implement your own serialization for those classes. It is unlikely this is worth the extra effort.
BTW: If you have a nested class, the outer class needs to be Serializable as well as the nested class implicitly has a reference to it even if you don't use it. For this reason and others I suggest making nested classes static
whenever possible.
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