前面已经把类文件加载了出来,并且将字节流转化成了易用的数据结构,下面就是类的验证和准备阶段了。验证阶段在书中忽略了,所以这里只包括准备阶段。
准备阶段主要是给类变量分配空间,赋上默认值,static final变量赋上初始值。如下所示,用slot数组保存静态变量。
type Class struct {
。。。
staticSlotCount uint
staticVars Slots //类静态变量
}
Slot定义如下,静态变量都保存在slot中,32位的类型如int,float,boolean,char,引用等都占用一个slot,64位的long和double占用两个slot。Slots是Slot的数组类型,主要封装了Slot的设置和查询操作。
type Slot struct {
num int32
ref *heap.Object
}
type Slots []Slot
func (this Slots) SetInt(index uint, val int32) {
this[index].num = val
}
func (this Slots) GetInt(index uint) int32 {
return this[index].num
}
func (this Slots) SetFloat(index uint, val float32) {
this[index].num = int32(math.Float32bits(val))
}
func (this Slots) GetFloat(index uint) float32 {
return math.Float32frombits(uint32(this[index].num))