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.
java serialization inner-classes
tb189 Aug 22 2018-11-11T00: 00Z
source share