سؤال

I have the following class containing the fields specified below. My question is, must Admin, Worker and all my other self-defined classes implement Serializable for MyClass to be Serializable?

public class MyClass implements java.io.Serializable {
  private static final long serialVersionUID = 1L;
  ArrayList<Admin> admins;
  ArrayList<Worker> workers;
  ArrayList<Manager> managers;
  ArrayList<Secretary> secretaries;
  ArrayList<Category> categories;
  HashMap<Issue, HashMap<Category,Manager>> ManagedIssues;
  private static MyClass instance;
      ...
}
هل كانت مفيدة؟

المحلول

My question is, must Admin, Worker and all my other self-defined classes implement Serializable for MyClass to be Serializable?

Yes. They have to be.

ArrayList is already implements Serializable interface by default. But you need to implement Serializable interface for the types you are using.

Serializability of a class is enabled by the class implementing the java.io.Serializable interface. 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.

نصائح أخرى

As others have stated, if a class is marked Serializable, then everything inside needs to be marked Serializable too.

But in this case also, you really need to make sure you limit mutability of internal state. In other words, when taking a mutable object (like ArrayList) in (a constructor or a setter) or returning it (in a getter), make copies to protect the internal state of MyClass. This is always a good practice but especially so with Serializable.

Yes.

If you don't want that stuff to be serialized, mark it as transient.

If you are making a class serializable, then you have to make sure that everything falling in that class is also serializable. So you must make them serializable first.

Yes, but only if thoses lists / map are not empty. In this case serialization mechanizm will try to serialize collections' content.

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