Serializable a object properties too

3.6k Views Asked by At

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{
    // ...
}
4

There are 4 best solutions below

1
On BEST ANSWER

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.

0
On

Short answer: yes. Each object wihtin your serializable class MUST be serializable by itself. Otherwise all properties can't be restored or whatever.

Furthermore, you will also get an exception when trying to serialize this object.

0
On

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.

0
On

From doc

Classes that do not implement this interface will not have any of their state serialized or deserialized.

So yes.

Please read