使用Chronicle Wire序列化Java对象ByteBuffer

时间:2018-07-07 14:39:20

标签: chronicle chronicle-bytes

我一直在使用“ javolution”来帮助我创建可以序列化到nio.ByteBuffer的Java对象,该对象可以进一步映射到C结构。

如何使用Chronicle Wire实现相同目的?

1 个答案:

答案 0 :(得分:0)

您可以写入由Byte包装的ByteBuffer。

我在这里https://github.com/OpenHFT/Chronicle-Wire/blob/master/src/test/java/net/openhft/chronicle/wire/marshallable/ByteBufferMarshallingTest.java

添加了一些测试用例
@Test
public void writeReadByteBuffer() {
    Bytes<ByteBuffer> bytes = Bytes.elasticByteBuffer();
    Wire wire = new RawWire(bytes);

    AClass o1 = new AClass(1, true, (byte) 2, '3', (short) 4, 5, 6, 7, 8, "nine");

    o1.writeMarshallable(wire);

    AClass o2 = ObjectUtils.newInstance(AClass.class);
    o2.readMarshallable(wire);

    assertEquals(o1, o2);
}

@Test
public void writeReadViaByteBuffer() {
    Bytes<ByteBuffer> bytes = Bytes.elasticByteBuffer();
    Wire wire = new RawWire(bytes);

    AClass o1 = new AClass(1, true, (byte) 2, '3', (short) 4, 5, 6, 7, 8, "nine");

    o1.writeMarshallable(wire);

    ByteBuffer bb = bytes.underlyingObject();
    bb.position((int) bytes.readPosition());
    bb.limit((int) bytes.readLimit());

    Bytes<ByteBuffer> bytes2 = Bytes.elasticByteBuffer();
    bytes2.ensureCapacity(bb.remaining());

    ByteBuffer bb2 = bytes2.underlyingObject();
    bb2.clear();

    bb2.put(bb);
    // read what we just wrote
    bytes2.readPosition(0);
    bytes2.readLimit(bb2.position());

    Wire wire2 = new RawWire(bytes2);

    AClass o2 = ObjectUtils.newInstance(AClass.class);
    o2.readMarshallable(wire2);
    assertEquals(o1, o2);
}

但是,如果您只打算使用RawWire,则最好extend设置AbstractBytesMarshallable,而不要使用Wire进行序列化。

@Test
public void writeReadBytesViaByteBuffer() {
    Bytes<ByteBuffer> bytes = Bytes.elasticByteBuffer();

    BClass o1 = new BClass(1, true, (byte) 2, '3', (short) 4, 5, 6, 7, 8, "nine");

    o1.writeMarshallable(bytes);

    ByteBuffer bb = bytes.underlyingObject();
    bb.position((int) bytes.readPosition());
    bb.limit((int) bytes.readLimit());

    Bytes<ByteBuffer> bytes2 = Bytes.elasticByteBuffer();
    bytes2.ensureCapacity(bb.remaining());

    ByteBuffer bb2 = bytes2.underlyingObject();
    bb2.clear();

    bb2.put(bb);
    // read what we just wrote
    bytes2.readPosition(0);
    bytes2.readLimit(bb2.position());

    BClass o2 = ObjectUtils.newInstance(BClass.class);
    o2.readMarshallable(bytes2);
    assertEquals(o1, o2);
}