3

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
{

}
4

1 回答 1

3

当你连载的时候new A()bnull这样的B

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

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

    private B b = new B();
于 2021-01-15T00:06:05.527 回答