java - Java 常量池的目的是什么?

标签 java vm-implementation class-constants

我目前正在尝试更深入地研究 Java 虚拟机的规范。我一直在阅读Inside the JVM book online还有一个我似乎无法理解的令人困惑的抽象:常量池。这是本书的摘录:

For each type it loads, a Java virtual machine must store a constant pool. A constant pool is an ordered set of constants used by the type, including literals (string, integer, and floating point constants) and symbolic references to types, fields, and methods. Entries in the constant pool are referenced by index, much like the elements of an array. Because it holds symbolic references to all types, fields, and methods used by a type, the constant pool plays a central role in the dynamic linking of Java programs

我有几个关于上述和一般CP的问题:

  1. CP 是否位于每种类型的 .class 文件中?
  2. 作者所说的“符号引用”是什么意思?
  3. 简单来说,常量池的用途是什么?

最佳答案

常量池是 .class 文件(及其内存表示)的一部分,其中包含运行该类的代码所需的常量。

这些常量包括程序员指定的文字和编译器生成的符号引用。符号引用基本上是从代码中引用的类、方法和字段的名称。 JVM 使用这些引用将您的代码链接到它所依赖的其他类。

比如下面的代码

System.out.println("Hello, world!");

产生以下字节码(javap 输出)

0:   getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;              
3:   ldc     #3; //String Hello, world!                                                  
5:   invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V

#n 这里是对常量池的引用。 #2 是对 System.out 字段的符号引用,#3Hello, world! 字符串和#4 是对 PrintStream.println(String) 方法的符号引用。

如您所见,符号引用不仅仅是名称 - 例如,对方法的符号引用还包含有关其参数(Ljava/lang/String;)和返回类型(V 表示 void)。

您可以通过为该类运行 javap -verbose 来检查该类的常量池。

关于java - Java 常量池的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10209952/

相关文章:

Ruby 类方法或常量,最佳实践

java - 数组总结(工作代码),不抓一行代码

vm-implementation - 我将如何编写虚拟机

Android Runtime(ART) 是虚拟机?

php - 在类常量 PHP 中组合位标志

excel - 为 Excel VBA 创建常量库的理想方法是什么?

java - 如何通过电子邮件发送谷歌应用程序引擎日志文件?

java - JPA-EclipseLink 中 @NamedQuery 和 @NamedNativeQuery 的区别

java - 使用 Mockito 跳过方法执行

assembly - x86 最快的虚拟机设计是什么?