Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: The keyword "this" and Serialization

Tags:

java

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();
like image 487
d-_-b Avatar asked Jun 01 '26 14:06

d-_-b


1 Answers

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]

like image 194
Sumit Singh Avatar answered Jun 03 '26 04:06

Sumit Singh