I'm writing a small serialization utility and I would like to calculate how many bytes I need to reserve to write an object to a byte array. Let's say I have a class with a few fields/getters like
int age;
String name;
Colour colour;
boolean active;
...
I thought I could use reflection to iterate over fields and look what size they have, but all I can do is check whether they are primitive. Which is a start, since I would use a short as an offset for Objects. Okay, I could use
if(field.getType() == int.class) {
size = Integer.BYTES;
}
or use a map. It would not be that hard, since I only need to know the size of primitives. But out of curiosity: Is there any direct way?
edit to clarify: I am using it to serialize data, basically like DataOutput/InputStream, but with some tweaks I wanted for myself.
The API class looks like this:
public final void write(int i) {
checkBounds(Integer.BYTES);
PrimitiveWriteUtil.write(i, data, marker);
advance(Integer.BYTES);
}
The actual work is done by a utility class:
public static void write(int i, byte[] target, int pos) {
target[pos] = (byte) ((i >>> 24) & 0xFF);
target[pos + 1] = (byte) ((i >>> 16) & 0xFF);
target[pos + 2] = (byte) ((i >>> 8) & 0xFF);
target[pos + 3] = (byte) ((i >>> 0) & 0xFF);
}
So, I want to know the required size of my byte array, so I can avoid the effort of checking and resizing later.