計算Java中Object的大小我想記錄一個對象占用多少內(nèi)存(以字節(jié)為單位)(我正在比較數(shù)據(jù)結(jié)構(gòu)的大小),似乎沒有方法可以在Java中執(zhí)行此操作。據(jù)說,C / C ++有sizeOf()方法,但這在Java中是不存在的。我嘗試Runtime.getRuntime().freeMemory()在創(chuàng)建對象之前和之后記錄JVM中的空閑內(nèi)存,然后記錄差異,但它只會給出0或131304,而不管結(jié)構(gòu)中的元素數(shù)量是什么。請幫忙!
3 回答

慕田峪7331174
TA貢獻(xiàn)1828條經(jīng)驗 獲得超13個贊
本java.lang.instrument.Instrumentation
類提供了一個很好的方式來獲得一個Java對象的大小,但它需要你定義一個premain
與一個Java代理運行程序。當(dāng)您不需要任何代理時,這非常無聊,然后您必須為您的應(yīng)用程序提供虛擬Jar代理。
所以我得到了另一種使用Unsafe
該類的替代解決方案sun.misc
。因此,根據(jù)處理器體系結(jié)構(gòu)考慮對象堆對齊并計算最大字段偏移量,您可以測量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
提交
取消