gpt4 book ai didi

java - ObjectOutput 抛出 java.io.NotSerializedException

转载 作者:行者123 更新时间:2023-12-02 08:37:53 25 4
gpt4 key购买 nike

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

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.NotSerializedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13412456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com