Java: The keyword "this" and Serialization

Viewed 62

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();
1 Answers
Related