ObjectOutput throws java.io.NotSerializableException



这是即将序列化为字节数组的类。

public class DummyClass implements Serializable
{
    private static transient final long serialVersionUID    = -8483859843874771619L;
    public String   y;
    public DummyClass(String y)
    {
        this.y = y;
    }
    public String getY()
    {
        return this.y;
    }
}

这是序列化执行测试

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = null;
    byte[] bs = null;
    try
    {
        DummyClass dummyClass = new DummyClass("World I Salute you");
        out = new ObjectOutputStream(bos);
        out.writeObject(dummyClass); // <--- Throws exception here
        bs = bos.toByteArray();
    }
    finally
    {
        out.close();
        bos.close();
    }

关于堆栈跟踪:

java.io.NotSerializableException: tests.DummyClassTest
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at tests.DummyClassTest.dummyTest(DummyClassTest.java:109)

显而易见的问题是我做错了什么?

干杯。

编辑

全班

public class DummyClassTest
{
    public class DummyClass implements Serializable
    {
        private static transient final long serialVersionUID    = -8483859843874771619L;
        public String   y;
        public DummyClass(String y)
        {
            this.y = y;
        }
        public String getY()
        {
            return this.y;
        }
    }
    @Test
    public void dummyTest() throws IOException
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = null;
        byte[] bs = null;
        try
        {
            DummyClass dummyClass = new DummyClass("World I Salute you");
            out = new ObjectOutputStream(bos);
            out.writeObject(dummyClass);
            bs = bos.toByteArray();
        }
        finally
        {
            out.close();
            bos.close();
        }
    }
}

静态内部类具有对其外部类实例的隐式引用。因此,当您序列化 DummyClass 时,您也在序列化对拥有它的 DummyClassTest 实例的隐式引用。

将 DummyClass 定义为顶级类(非嵌套)或静态内部类,一切都将按预期工作。

以下:

public class DummyClassTest {
    public class DummyClass {
    }
}

或多或少等同于

public class DummyClassTest {
}
public class DummyClass {
    private DummyClassTest outerInstance;
}

相关内容

  • 没有找到相关文章

最新更新