本文主要讲述三种常量池: Class 常量池、字符串常量池、还有基本类型常量池。
默认 jdk 版本:jdk 1.8
Class 常量池
Class 常量池可以理解为 Class 文件中的资源仓库, Class 文件中除了包含类的版本、字段、方法、接口等描述信息外,还有一项就是 常量池(constant pool table), 用于存放编译期生成的各种 字面量(Literal)和符号引用(Symbolic References)
我们一般会通过 javap 命令生成可读的 JVM 字节码指令文件:
Classfile /Users/zhengsh/cqvie.edu.cn/ssm-salt/ssm-salt-jvm/src/main/java/cn/edu/cqvie/jvm/Math.class
Last modified 2021年2月4日; size 499 bytes
MD5 checksum 037cef02562301117a47bc10b250c770
Compiled from "Math.java"
public class cn.edu.cqvie.jvm.Math
minor version: 0
major version: 52
flags: (0x0021) ACC_PUBLIC, ACC_SUPER
this_class: #2 // cn/edu/cqvie/jvm/Math
super_class: #7 // java/lang/Object
interfaces: 0, fields: 0, methods: 3, attributes: 1
Constant pool:
#1 = Methodref #7.#18 // java/lang/Object."<init>":()V
#2 = Class #19 // cn/edu/cqvie/jvm/Math
#3 = Methodref #2.#18 // cn/edu/cqvie/jvm/Math."<init>":()V
#4 = Fieldref #20.#21 // java/lang/System.out:Ljava/io/PrintStream;
#5 = Methodref #2.#22 // cn/edu/cqvie/jvm/Math.compute:()I
#6 = Methodref #23.#24 // java/io/PrintStream.println:(I)V
#7 = Class #25 // java/lang/Object
#8 = Utf8 <init>
#9 = Utf8 ()V
#10 = Utf8 Code
#11 = Utf8 LineNumberTable
#12 = Utf8 compute
#13 = Utf8 ()I
#14 = Utf8 main
#15 = Utf8 ([Ljava/lang/String;)V
#16 = Utf8 SourceFile
#17 = Utf8 Math.java
#18 = NameAndType #8:#9 // "<init>":()V
#19 = Utf8 cn/edu/cqvie/jvm/Math
#20 = Class #26 // java/lang/System
#21 = NameAndType #27:#28 // out:Ljava/io/PrintStream;
#22 = NameAndType #12:#13 // compute:()I
#23 = Class #29 // java/io/PrintStream
#24 = NameAndType #30:#31