Java:关键字“this”和序列化
我有一个简单的类,如下所示
我想用这个类实现的就是将实例序列化为字节数组,但我一直得到java.io.NotSerializableException
我的代码怎么了
这只是指向调用构造函数时创建的实例的指针,而不是实际的实例对象吗
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();
# 1 楼答案
从NotSerializableException
您需要在类中实现可序列化接口
请参见此处的输出ideone.com