Reputation: 1353
I would like to serialize a non-static inner class in my java program. Though this is not allowed because my inner class (by default) has a reference to its outer class (which in this case is not serializable) so if I try to serialize it I get a NullPointerException for the outer class.
So is there a way to override the reference to the outer class and set it to transient so that it is not serialized by initialized every time and object of the inner class is created?
Upvotes: 0
Views: 1624
Reputation: 121702
You can't: if your inner class is not static
, its initialization state depends on the instance of the outer class by definition. This, because you could not get an instance of your inner class without having an instance of the outer class to begin with.
And since the outer class is not Serializable
, you cannot serialize the instance of the outer class, therefore you cannot serialize the instance of the inner class.
Or just make the inner class static and be done with it...
Upvotes: 2
Reputation:
The automated serialization has a few negative parts: if you change the field name or you change the visibility of a field, than the deserialization will not work, more over: it will take a lot more space objects saved "automatically". For this reason almost always I am serializing / deserializing classes manually: write an int, write a string than read it back. With this method you can write the none static innner class deserialization as you want it
Upvotes: 0
Reputation: 200138
You can't make the implicit reference to the enclosing instance transient
, but what you could do is redesign to make it a nested (static) class and pass the enclosing instance explicitly in a constructor argument. Then you'd need an explicit variable in your nested class, which you'd be allowed to tag as transient
.
Upvotes: 2