2

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

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();
        }
    }
}
4

1 回答 1

8

非静态内部类具有对其外部类实例的隐式引用。所以当你序列化 DummyClass 时,你也在序列化这个对拥有它的 DummyClassTest 实例的隐式引用。

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

以下:

public class DummyClassTest {
    public class DummyClass {
    }
}

或多或少等同于

public class DummyClassTest {
}

public class DummyClass {
    private DummyClassTest outerInstance;
}
于 2012-11-16T07:57:24.077 回答