类变量解析:静态/非静态偏移量

本文详细介绍了JVM在解析类变量时如何计算静态和非静态变量的偏移量。解析过程中,JVM会根据常量池信息分配内存并保存类变量。静态变量偏移量的计算按数据类型顺序累加,而非静态变量偏移量的计算则更为复杂,涉及到不同的分配方式。此外,内存对齐是关键,以确保在不同平台上的效率和兼容性。后续文章将进一步讨论内存对齐的实现策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

偏移量

静态变量偏移量

非静态变量偏移量

内存对齐


      根据常量池中的信息,JVM先进行内存分配,构建出constantPoolOop对象,为其分配足够的空间来保存字节码文件信息,再进行解析工作。在加载某一个类时,从常量池中还原出类里面定义的变量和方法,将它们保存到内存中,具体在constantPoolOop对象中的tag数组(存放一些索引等)和data区,在保存数据后,根据ClassFileParser::parseClassFile()链路,一系列如魔数解析、父类、接口解析之后,便到了类变量的解析,虽然常量池解析已经把Java类的变量和方法都保存到了内存中,但这些数据还需要被JVM进一步解析,在链路中解析类变量的函数是parse_fields()。

      ClassFileParser::parseClassFile()里解析完常量池,父类和接口后,接着下一步解析类变量:

void ClassFileParse::parseClassFile(constantPoolHandle cp, int length, TRAPS) {
	//....
	struct FieldAllocationCount fac = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
	objArrayHandle fields_annotations;
	typeArrayHandle fields = parse_fields(cp, access_flags.is_interface(), 
		&fac, &fields_annotations, CHECK_(nullHnalde));
	//....
}

      首先初始化一个FieldAllocationCount结构体类变量fac,该结构体里面记录了5种静态类型变量和5种非静态类型变量的数量,所以一开始全部值都设为0:

struct FieldAllocationCount {
	unsigned int static_oop_count;
	unsigned int static_byte_count;
	unsigned int static_short_count;
	unsigned int static_word_count;
	unsigned int static_double_count;
	unsigned int nonstatic_oop_count;
	unsigned int nonstatic_byte_count;
	unsigned int nonstatic_short_count;
	unsigned int nonstatic_word_count;
	unsi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值