Kryo (missing no-arg constructor): java.nio.HeapByteBuffer

While serializing ByteBuffer using Kryo we will run into the following issue.

Class cannot be created (missing no-arg constructor): java.nio.HeapByteBuffer

To fix this we can create a custom serializer that will take a ByteBuffer and serialize it to and from Kryo. Serializer is rather simple all we need is two pieces of data, length of the buffer and actual buffer.

public class ByteBufferSerializer extends Serializer<ByteBuffer>
{
 
    @Override
    public void write(final Kryo kryo, final Output output, final ByteBuffer object)
    {
        output.writeInt(object.capacity());
        output.write(object.array());
    }
 
    @Override
    public ByteBuffer read(final Kryo kryo, final Input input, final Class<ByteBuffer> type)
    {
        final int length = input.readInt();
        final byte[] buffer = new byte[length];
        input.read(buffer, 0, length);
 
        return ByteBuffer.wrap(buffer, 0, length);
    }   
}

Last step is to register out new serializer with Kryo.

 
kryo.register(ByteBuffer.allocate(0).getClass(), new ByteBufferSerializer()); 

Here we use a small trick ByteBuffer.allocate(0).getClass() to get concrete implementation of the ByteBuffer. We have to do this because java.nio.HeapByteBuffe is package protected and we can’t get access to it outside the java.nio package.

Leave a Comment

Your email address will not be published. Required fields are marked *