Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializable a object properties too

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{
    // ...
}
like image 939
nimo23 Avatar asked Dec 16 '22 18:12

nimo23


2 Answers

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.

like image 68
Jesper Avatar answered Dec 27 '22 10:12

Jesper


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.

like image 32
Peter Lawrey Avatar answered Dec 27 '22 10:12

Peter Lawrey