【问题标题】:Why I don't have there NotSerializableException?为什么我没有 NotSerializableException?
【发布时间】:2021-04-20 01:02:44
【问题描述】:

为什么我没有NotSerializableException,因为在类A 中没有序列化我有private B b,但我知道如果类实现Serializable,所有复合类都必须实现Serializable /Externalizable 也是。

import java.io.*;

public class Test
{
    public static void main(String[] args) throws IOException
    {
        FileOutputStream fileOutput = new FileOutputStream("a.dat");
        ObjectOutputStream outputStream = new ObjectOutputStream(fileOutput);
        outputStream.writeObject(new A());
        fileOutput.close();
        outputStream.close();
    }
}

class A implements Serializable
{
    private int age;
    private B b;
}

class B
{

}

【问题讨论】:

    标签: java serializable externalizable


    【解决方案1】:

    当您序列化 new A() 时,bnull 所以不是 B

    重要的是运行时类型 - 例如,您可以使用 class BDerived extends B implements java.ui.Serializable。或者 ArrayList 可以从 List 字段引用序列化。

    如果您使用非null、不可序列化的类型初始化b,您会看到异常。比如

        private B b = new B();
    

    【讨论】:

      猜你喜欢
      • 2013-07-15
      • 1970-01-01
      • 2015-10-08
      • 2015-09-28
      • 2014-08-03
      • 2020-02-28
      • 2019-12-21
      • 1970-01-01
      相关资源
      最近更新 更多