I have a Java class, like:
class Foo implements IBar
{
// Methods ..
// A bunch of fields of primitive types (int, String)
int f1;
int f2;
String f3;
// ...
}
I want to pack all these fields to the byte array (don’t ask me why, this restriction is introduced by the C++ side that sends me data in such format).
The only way I found is to use ByteBuffer. But it is the worst I can thinks of. The code looks like:
ByteBuffer buf = ByteBuffer.allocate(4);
int offset = 0;
buf.putInt(f1);
System.arraycopy(buf.array(), 0, rawHeader, offset, 4);
offset += 4;
// A bunch of lines here (pack all other fields)
Does anyone know more suitable way of doing it? Thanks.
Use a
DataOutputStreamwrapping aByteArrayOutputStream.Or, if you prefer, make your class implement
Serializableand use anObjectOutputStreamwrapping aByteArrayOutputStream. This will of course make a byte array readable only by Java.