![](/img/trans.png)
[英]Java: how to serialize object into byte array with as few output bytes as possible?
[英]How to Serialize object to byte array with compact bytes in java
例如,我有一個具有short,byte,int類型成員變量的類。
class A{
short a;
byte b;
int c;
}
如果我序列化或轉換為字節數組,則該數組為意外值。
如果值像
A a = new A();
a.a = 3;
a.b = 0x02;
a.c = 15;
然后,我希望它的字節為
00 03 02 00 00 00 0F
那么...如何像這樣序列化對象?
它需要我的套接字服務器...其他語言
如果需要字節數組,可以執行此操作。 但是,如果使用的是DataOutputStream之類的東西,則最好只調用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);
您可以使用反射來獲取類中的所有fields
,並將它們循環以轉換為字節數組。
如果您所有的字段都是Number
(即不是引用也不是boolean
),則可以將它們轉換並收集為Byte
List
,如下所示:
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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.