سؤال

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.

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.

From doc

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

So yes.

Please read

Serializable Yes because :

Classes that do not implement this interface will not have any of their state
serialized or deserialized. All subtypes of a serializable class are themselves 
serializable. The serialization interface has no methods or fields and serves 
only to identify the semantics of being serializable.

If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a NotSerializableException will be thrown at runtime

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top