如何序列化ByteBuffer

jtn*_*ire 6 java bytebuffer rmi

我希望使用RMI在网络上发送java.nio.ByteBuffer,但是ByteBuffer不可序列化.我尝试过以下自定义类无济于事:

public class NetByteBuffer implements java.io.Serializable {

ByteBuffer buffer;

public NetByteBuffer(ByteBuffer buffer) {
    this.buffer = buffer;
}

public ByteBuffer getByteBuffer() {
    return this.buffer;
}
Run Code Online (Sandbox Code Playgroud)

}

客户端仍然获得不可序列的异常.有任何想法吗?

谢谢

Boz*_*zho 6

你不能.你最好获得byte[]并发送它,然后ByteBuffer在另一边重建它.你当然失去了它作为缓冲区的优势.

  • 如果您在没有特定原因的情况下使用`ByteBuffer`,那么使用字节数组可能是安全的;) (3认同)

Car*_*des 5

就像其他人所说的那样,ByteBuffer 是字节缓冲区的包装,因此如果您需要序列化您的类,最好更改为 byte[] 并在将数据读/写到该 bean 的类中使用 ByteBuffer。

但是,如果您需要序列化 ​​ByteBuffer 属性(例如使用 Cassandra blob),您始终可以实现自定义序列化(检查此 url http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html)。

要点是:

  1. 将 ByteBuffer 标记为瞬态(因此默认情况下不会序列化)
  2. 实现您自己的序列化读/写,其中序列化时为 ByteBuffer --> byte[],反序列化时为 byte[] --> ByteBuffer。

尝试这门课程,让我知道这是否适合您:

public class NetByteBuffer implements java.io.Serializable {
    private static final long serialVersionUID = -2831273345165209113L;

    //serializable property
    String anotherProperty;

    // mark as transient so this is not serialized by default
    transient ByteBuffer data;

    public NetByteBuffer(String anotherProperty, ByteBuffer data) {
        this.data = data;
        this.anotherProperty = anotherProperty;
    }

    public ByteBuffer getData() {
        return this.data;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        // write default properties
        out.defaultWriteObject();
        // write buffer capacity and data
        out.writeInt(data.capacity());
        out.write(data.array());

    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        //read default properties
        in.defaultReadObject();

        //read buffer data and wrap with ByteBuffer
        int bufferSize = in.readInt();
        byte[] buffer = new byte[bufferSize];
        in.read(buffer, 0, bufferSize);
        this.data = ByteBuffer.wrap(buffer, 0, bufferSize);
    }

    public String getAnotherProperty() {
        return anotherProperty;
    }

}
Run Code Online (Sandbox Code Playgroud)