Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to create message structures in Java?

If, for example, I am given requirements of message structure similar to the one down below:

  • header 28-bytes
    • consumer 2-bytes
    • type 4-bytes
    • ...
  • payload 64-bytes

Are there any libraries in Java to make it done quicker?

Or I have to create it manually as a separate class with byte arrays and setters/getters?

like image 787
Arturs Vancans Avatar asked Oct 22 '22 21:10

Arturs Vancans


1 Answers

You can probably benefit from the utility methods in the ByteBuffer class instead of handling a byte array directly. You'll find methods for getting and setting multi-byte integers (e.g. getShort, putInt, putLong) and you can also control the byte order (big or little endian).

You can then wrap the ByteBuffer in another class with meaningful method names, e.g:

int getType() {
  return bb.getInt(2); // offset 2
}

void setType(int type) {
  bb.putInt(2, type);
}
like image 197
jarnbjo Avatar answered Nov 14 '22 23:11

jarnbjo