为什么可序列化的内部类不可序列化? [英] Why is a serializable inner class not serializable?

查看:1437
本文介绍了为什么可序列化的内部类不可序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

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

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?

编辑:例如,访问外部类可能是仅在序列化之前需要。好吧,编译器无法知道,但我认为这就是 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.

推荐答案


如果InnerClass需要此访问权限怎么办?

what if InnerClass needs this access?

然后它需要外部类实例,并且必须与内部类一起序列化。

Then it needs the outer class instance, and it must be serialized along with the inner class.


有没有办法在没有封闭类的情况下序列化非静态内部类,例如通过引用外部类瞬态?

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?

否。当您反序列化这样的类然后尝试调用外部类的实例方法时会发生什么? A NullPointerException

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

这篇关于为什么可序列化的内部类不可序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆