我已经准备好下课
public class MyFields {
public byte fieldA = 0x00;
public int fieldB = 50;
public long fieldC = 0x4014B4F300F0A379L;
}
我想将此类中的字段值解析为字节数组。 我的方法是:
public byte[] convertFieldToBytes()
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
MyFields myFields = new MyFields();
for (Field field : myFields.getClass().getDeclaredFields()) {
Class fieldtype = field.getType();
if (fieldtype == int.class) {
baos.write(ByteBuffer.allocate(Integer.BYTES).putInt((int) field.get(myFields)).array());
}
else if (fieldtype == long.class) {
baos.write(ByteBuffer.allocate(Long.BYTES).putLong((long) field.get(myFields)).array());
}
else if (fieldtype == byte.class) {
baos.write(ByteBuffer.allocate(Byte.BYTES).put((byte) field.get(myFields)).array());
}
}
return baos.toByteArray();
}
但是此方法包含很多IF语句!我想使其更短,但我不能删除强制转换-它将导致异常。 我需要类似的东西:
public byte[] convertFieldToBytes()
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
MyFields myFields = new MyFields();
for (Field field : myFields.getClass().getDeclaredFields()) {
baos.write(ByteBuffer.put(field.get(myFields)).array());
}
return baos.toByteArray();
}
如何正确执行操作?