在Java中获取数据类型大小(sizeof)的最佳实践

我希望存储一个ByteBuffer的双精度和整数列表,它要求分配大小。 我想写一些像C语法的东西

int size=numDouble*sizeof(double)+numInt*sizeof(int); 

但Java中没有sizeof 。 以字节计算大小的最佳做法是什么? 我应该硬编码吗?

(如果您使用的是Java 8或更高版本,请务必查看@Frank Kusters的答案 !)

所有原始包装器都有一个SIZE常量,它以位为单位,而不是字节。

所以在给出的例子中,它将是:

 int size=(numDouble*Double.SIZE+numInt*Integer.SIZE) / Byte.SIZE; 

或者,如果你想避免分裂:

 int size=numDouble*(Double.SIZE/Byte.SIZE)+numInt*(Integer.SIZE/Byte.SIZE); 

(因为除法有两个常量,所以它是在编译时完成的。)

从Java 8开始,所有基本类型的包装类( Boolean除外)都有一个BYTES字段。 所以在你的情况下:

 int size = numDouble * Double.BYTES + numInt * Integer.BYTES; 

文档: http : //docs.oracle.com/javase/8/docs/api/java/lang/Integer.html

编写自己的方法。 在Java中,数据类型与平台无关,总是大小相同:

 public static int sizeof(Class dataType) { if (dataType == null) throw new NullPointerException(); if (dataType == int.class || dataType == Integer.class) return 4; if (dataType == short.class || dataType == Short.class) return 2; if (dataType == byte.class || dataType == Byte.class) return 1; if (dataType == char.class || dataType == Character.class) return 2; if (dataType == long.class || dataType == Long.class) return 8; if (dataType == float.class || dataType == Float.class) return 4; if (dataType == double.class || dataType == Double.class) return 8; return 4; // 32-bit memory pointer... // (I'm not sure how this works on a 64-bit OS) } 

用法:

 int size = numDouble * sizeof(double.class) + numInt * sizeof(int.class); 

更好的解决方案可能是不模拟C语法并使用带有嵌套ByteArrayOutputStream的ObjectOutputStream来生成一个字节数组,然后可以将其写入ByteBuffer。

Java中的大小始终相同。 您可以对其进行硬编码,但您只需执行此操作,因为您正在使用ByteBuffer中的字节。 如果您使用double[]DoubleBuffer ,则不需要这些。

你也可以使用sizeof4j库来获得你需要的double的sizeof SizeOf.doubleSize()