计算Java中Object的大小我想记录一个对象占用多少内存(以字节为单位)(我正在比较数据结构的大小),似乎没有方法可以在Java中执行此操作。据说,C / C ++有sizeOf()方法,但这在Java中是不存在的。我尝试Runtime.getRuntime().freeMemory()在创建对象之前和之后记录JVM中的空闲内存,然后记录差异,但它只会给出0或131304,而不管结构中的元素数量是什么。请帮忙!
3 回答

慕田峪7331174
TA贡献1828条经验 获得超13个赞
本java.lang.instrument.Instrumentation
类提供了一个很好的方式来获得一个Java对象的大小,但它需要你定义一个premain
与一个Java代理运行程序。当您不需要任何代理时,这非常无聊,然后您必须为您的应用程序提供虚拟Jar代理。
所以我得到了另一种使用Unsafe
该类的替代解决方案sun.misc
。因此,根据处理器体系结构考虑对象堆对齐并计算最大字段偏移量,您可以测量Java对象的大小。在下面的示例中,我使用辅助类UtilUnsafe
来获取sun.misc.Unsafe
对象的引用。
private static final int NR_BITS = Integer.valueOf(System.getProperty("sun.arch.data.model"));private static final int BYTE = 8;private static final int WORD = NR_BITS/BYTE;private static final int MIN_SIZE = 16; public static int sizeOf(Class src){ // // Get the instance fields of src class // List<Field> instanceFields = new LinkedList<Field>(); do{ if(src == Object.class) return MIN_SIZE; for (Field f : src.getDeclaredFields()) { if((f.getModifiers() & Modifier.STATIC) == 0){ instanceFields.add(f); } } src = src.getSuperclass(); }while(instanceFields.isEmpty()); // // Get the field with the maximum offset // long maxOffset = 0; for (Field f : instanceFields) { long offset = UtilUnsafe.UNSAFE.objectFieldOffset(f); if(offset > maxOffset) maxOffset = offset; } return (((int)maxOffset/WORD) + 1)*WORD; }class UtilUnsafe { public static final sun.misc.Unsafe UNSAFE; static { Object theUnsafe = null; Exception exception = null; try { Class<?> uc = Class.forName("sun.misc.Unsafe"); Field f = uc.getDeclaredField("theUnsafe"); f.setAccessible(true); theUnsafe = f.get(uc); } catch (Exception e) { exception = e; } UNSAFE = (sun.misc.Unsafe) theUnsafe; if (UNSAFE == null) throw new Error("Could not obtain access to sun.misc.Unsafe", exception); } private UtilUnsafe() { }}
添加回答
举报
0/150
提交
取消