Why isn't a serializable inner class serializable?

The following code:

public class TestInnerClass { public static void main(String[] args) throws IOException { new TestInnerClass().serializeInnerClass(); } private void serializeInnerClass() throws IOException { File file = new File("test"); InnerClass inner = new InnerClass(); new ObjectOutputStream(new FileOutputStream(file)).writeObject(inner); } private class InnerClass implements Serializable { private static final long serialVersionUID = 1L; } } 

throws the following exception:

 Exception in thread "main" java.io.NotSerializableException: TestInnerClass 

I assume that the inner class has a TestInnerClass.this field that allows it to access the TestInnerClass fields and methods. Declaring an inner class static solves it , but what if InnerClass needs this access? Is there a way to serialize a non-static inner class without an enclosing class, for example. by making a reference to the transient outer class?

edit: for example, access to an external class may be required only before serialization. OK, the compiler cannot know this, but I wondered why the transient keyword exists.

+17
java serialization inner-classes
Aug 22 2018-11-11T00:
source share
3 answers

What if InnerClass needs this access?

Then it needs an instance of the outer class, and it needs to be serialized along with the inner class.

Is there a way to serialize a non-static inner class without an enclosing class, for example. by reference to the transition class of the outer class?

No. What happens when you deserialize such a class and then try to call the instance method of the outer class? A NullPointerException ?

+18
Aug 22
source share

how to make serializable TestInnerClass?

 public class TestInnerClass implements Serializable { } 
+1
Aug 22 2018-11-11T00:
source share

InnerClass cannot be serialized because to create it (as required for deserialization) you need a reference to an instance of the outer class

Instances of inner classes cannot exist without an instance of the outer class.

ie

 OuterClass o = new OuterClass(); OuterClass.InnerClass o_i = o.new InnerClass(); 

If you use a static inner class, you can serialize the static inner class. Instances of static inner classes can be created stand-alone.

ie

 OuterClass o = new OuterClass(); OuterClass.InnerClass i = new OuterClass.InnerClass(); 
0
Jun 29 '17 at 7:20
source share



All Articles