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

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;
}

关于java - ObjectOutput引发java.io.NotSerializableException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13412456/

10-11 06:17