简体   繁体   中英

How to Serialize object to byte array with compact bytes in java

For example, I have a class that has short, byte, int type member variable.

class A{
    short a;
    byte b;
    int c;
}

If I serialize or convert to byte array, the Array is unexpected value.

if values like,

A a = new A();
a.a = 3;
a.b = 0x02;
a.c = 15;

then, I expect its bytes as,

00 03 02 00 00 00 0F

So... How to Serialize Object like that?

It needs my socket server... other language

If you want a byte array you can do this. However if you are using something like DataOutputStream it's best to just call writeInt, writeShort, ...

A a = new A();
a.a = 3;
a.b = 0x02;
a.c = 15;

ByteBuffer bb = ByteBuffer.allocate(7).order(ByteOrder.BIG_ENDIAN);
bb.putShort(a.a).put(a.b).putInt(a.c).flip();
byte[] buffer = bb.array();
for (byte b : buffer)
    System.out.printf("%02X ", b);

You can use reflection to get all fields in the class, and loop them to convert to an array of bytes.

If all your fields are Number (ie not references nor boolean ), you can convert and collect them to a List of Byte as follows:

List<Byte> list = new ArrayList<>();
for (Field field : A.class.getDeclaredFields()) {
    // Do something else if field is not a Number
    // ...

    // Otherwise, convert and collect into list
    Number n = (Number) field.get(a);
    int size = n.getClass().getDeclaredField("BYTES").getInt(null);
    IntStream.range(0, size)
        .mapToObj(i -> (byte) (n.longValue() >> 8*(size-i-1)))
        .forEach(b -> list.add(b));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM