gpt4 book ai didi

Java:关键字 "this"和Serialization

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:08:06 26 4
gpt4 key购买 nike

我有一个简单的类,如下所示。

我想用这个类实现的所有目的是将实例序列化为字节数组,但我不断收到 java.io.NotSerializableException

我的代码有什么问题?

this 只是一个指向调用构造函数时创建的实例的指针,而不是实际的实例对象吗?

class XXX {
private String someStr;

public XXX(String someStr){
this.someStr = someStr;
}

public byte[] toByteArray(){
byte[] output = null;
try(ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(out)) {
stream.writeObject(this);
output = out.toByteArray();
}catch(Exception e){
}
return output;
}

}

XXX aX = new XXX("some string");
aX.toByteArray();

最佳答案

来自 NotSerializableException

Thrown when an instance is required to have a Serializable interface. The serialization runtime or the class of the instance can throw this exception. The argument should be the name of the class.

您需要在您的类中实现Serializable 接口(interface)

class XXX implements Serializable {
...
}

在这里查看输出 ideone.com

[-84, -19, 0, 5, 115, 114, 0, 6, 73, 100, 101, 111, 110, 101, 107, -60, 36, 124, 45, 63, 13, 80, 2, 0, 1, 76, 0, 7, 115, 111, 109, 101, 83, 116, 114, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 120, 112, 116, 0, 11, 115, 111, 109, 101, 32, 115, 116, 114, 105, 110, 103]

关于Java:关键字 "this"和Serialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36176817/

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