3

I have the following class definition which I want to save in a file, and all its fields are serializable, so why isn't the class serializable?

I've read in other responses that I don't need getters and setters, so I've omitted them from the class definition.

private class MyClass implements Serializable
{
    private static final long serialVersionUID = 314L;

    public HashMap<Long, String> allTags = new HashMap<Long, String>();
    public HashMap<String, String> notes = new HashMap<String, String>();
    public HashMap<String, ArrayList<Long>> tags = 
                                   new HashMap<String, ArrayList<Long>>();
}
ernest_k
  • 44,416
  • 5
  • 53
  • 99
Bogdan Alexandru
  • 5,394
  • 6
  • 34
  • 54
  • 3
    @AnishB. Can only be an inner class. There can't be a top-level class with the `private` access modifier. And here surely lies the answer: the enclosing class is not serializable or has non-serializable fields. – ernest_k Oct 19 '20 at 05:44
  • Does this answer your question? [Why does writeObject throw java.io.NotSerializableException and how do I fix it?](https://stackoverflow.com/questions/13895867/why-does-writeobject-throw-java-io-notserializableexception-and-how-do-i-fix-it) – Anish B. Oct 19 '20 at 05:45
  • Doesn this code really compile? `MyClass` can only be an inner class, and inner classes can't have static members. – user207421 Oct 19 '20 at 08:53

2 Answers2

2

Straight forward, the enclosing class needs to be Serializable.

Anish B.
  • 9,111
  • 3
  • 21
  • 41
  • 1
    Amazing, and interesting at the same time. So the enclosing class has to be Serializable even though I'm never saving that one? Why?!? Anyway, this explains why the exception on the console contained the name of the enclosing class, I thought that was just some weird printing... – Bogdan Alexandru Oct 19 '20 at 06:02
  • 3
    @BogdanAlexandru Because you are saving it. Every instance of an inner class has a hidden reference to the enclosing instance. – user207421 Oct 19 '20 at 08:53
0

If this is an inner class, make the outer class serializable and serialzie outer class instance

c7tt8nt2p
  • 64
  • 1
  • 5