How to serialize ByteBuffer

jtnire picture jtnire · Oct 21, 2010 · Viewed 9.2k times · Source

I wish to send a java.nio.ByteBuffer accross a network using RMI, however ByteBuffer isn't serializable. I've tried the following custom class to no avail:

public class NetByteBuffer implements java.io.Serializable {

ByteBuffer buffer;

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

public ByteBuffer getByteBuffer() {
    return this.buffer;
}

}

The client still gets a non-serialzable exception. Any ideas?

Thanks

Answer

Bozho picture Bozho · Oct 21, 2010

You can't. You'd better obtain the byte[] and send it instead and reconstruct the ByteBuffer on the other side. You are of course losing the advantages of it being a buffer.