Сериализовать объект Java ByteBuffer с помощью Chronicle Wire

Я использовал "javolution", который помогает мне создавать объекты Java, которые можно сериализовать в nio.ByteBuffer, которые затем могут быть сопоставлены со структурами C.

Как я могу добиться того же с помощью Chronicle Wire?


person user1545583    schedule 07.07.2018    source источник


Ответы (1)


Вы можете писать в ByteBuffer, который обернут Bytes.

Я добавил здесь несколько тестовых примеров 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, вам может быть лучше extending 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);
}
person Peter Lawrey    schedule 16.07.2018