有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    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.

    您需要在类中实现可序列化接口

    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]