1. 根據java的字節碼格式說明,常量池中每一項的大小不一樣的。運行時,若要通過數組索引獲取具體的一項時,
必須要經過一定的處理才能根據數組下標進行處理,具體的實現原理實際上就是空間換時間,可以參考kvm的實現:
每一項的定義,採用的是union的定義(會取最大的字節數進行內存分配)
/* Each of these represents one entry in the constant pool */ union constantPoolEntryStruct { struct { unsigned short classIndex; unsigned short nameTypeIndex; } method; /* Also used by Fields */ CLASS clazz; INTERNED_STRING_INSTANCE String; cell *cache; /* Either clazz or String */ cell integer; long length; NameTypeKey nameTypeKey; NameKey nameKey; UString ustring; };
2. 常量池的定義:
注意:這裏有多少個數組元素,實際上不確定的,這裏只是佔位而已,具體使用時是通過分配不同的
內存大小實現可變大小。
struct constantPoolStruct { union constantPoolEntryStruct entries[1]; };
typedef struct constantPoolStruct* CONSTANTPOOL; ConstantPool = (CONSTANTPOOL)callocPermanentObject(tableSize);