I have a simple class as shown below.
All what I want to achieve with this class is to make the instance serialized into a byte array, but I keep getting java.io.NotSerializableException.
What is wrong with my code?
Is this just a pointer to an instance created upon calling the constructor and not the actual instance object?
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();
From 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.
You need to implement Serializable interface in you class.
class XXX implements Serializable {
...
}
See the output here 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With