为什么可序列化内部类不可序列化?
以下代码:
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;
}
}
抛出以下异常:
Exception in thread "main" java.io.NotSerializableException: TestInnerClass
我猜内部类有一个 TestInnerClass.this 字段,允许它私有访问 TestInnerClass 的字段和方法。将内部类声明为静态解决了这个问题 ,但是如果 InnerClass
需要此访问权限怎么办?有没有办法在没有封闭类的情况下序列化非静态内部类,例如通过引用外部类transient
?
编辑:例如,仅在序列化之前才需要访问外部类。好吧,编译器无法知道这一点,但我认为这就是 transient
关键字存在的原因。
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 guess the inner class has a TestInnerClass.this
field that allows it private access to TestInnerClass
's fields and methods. Declaring the inner class static solves it, but what if InnerClass
needs this access? Is there a way to serialize a non-static inner class without the enclosing class, e.g. by making the reference to the outer class transient
?
edit: for example, access to the outer class could be needed only before serialization. OK, the compiler cannot know that, but I thought that's why the transient
keyword exists.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
然后它需要外部类实例,并且它必须与内部类一起序列化。
不。当您反序列化这样一个类,然后尝试调用外部类的实例方法时,会发生什么情况?空指针异常?
Then it needs the outer class instance, and it must be serialized along with the inner class.
No. What would happen when you deserialize such a class and then try to call an instance method of the outer class? A
NullPointerException
?让 TestInnerClass 可序列化怎么样?
how about make TestInnerClass serializable?
InnerClass 无法序列化,因为要实例化它(根据反序列化期间的要求),您需要引用外部类的实例
。没有外部类的实例,内部类的实例就不能存在。
即
如果使用静态内部类,则可以序列化静态内部类。静态内部类的实例可以独立创建。
IE
InnerClass cannot be serialised because to instantiate it (as required during 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.
i.e
If you use static inner class, it will be possible to serialise the static inner class. The instances of static inner classes can be created standalone.
i.e