这几天一直在玩Java反射和.class
格式。我目前正在学习 ldc
指令。
在 JVM 规范中我发现了我不理解的术语:symbolic reference,我有以下问题。
这是什么意思?
用在什么地方?
ldc
指令在哪些情况下加载符号引用?- Java 中是否有对应于该操作的任何代码?
最佳答案
如果您能准确引用文档中给您带来麻烦的部分,那将会很有帮助。既然你还没有,我将猜测你可能引用了哪些内容,来自 ldc 的文档。 :
Otherwise, if the run-time constant pool entry is a symbolic reference to a class (§5.1), then the named class is resolved (§5.4.3.1) and a reference to the Class object representing that class, value, is pushed onto the operand stack.
Otherwise, the run-time constant pool entry must be a symbolic reference to a method type or a method handle (§5.1). ...
此引用有指向 JVM 规范 (5.1) 另一部分的链接,该部分描述了运行时常量池:
a run-time data structure that serves many of the purposes of the symbol table of a conventional programming language implementation
这意味着运行时常量池以符号形式包含有关类的各个部分的信息:作为文本值。
因此,当 ldc
被赋予一个类的“符号引用”时,它被赋予常量池中 CONSTANT_Class_info
结构的索引。如果查看此结构的定义,您会发现它包含对类名的引用,该类名也保存在常量池中。
TL;DR:“符号引用”是可用于检索实际对象的字符串。
一个例子:
if (obj.getClass() == String.class) {
// do something
}
变成如下字节码:
aload_1
invokevirtual #21; //Method java/lang/Object.getClass:()Ljava/lang/Class;
ldc #25; //class java/lang/String
if_acmpne 20
在这种情况下,ldc
操作引用了一个以符号方式存储的类。当 JVM 执行此操作码时,它将使用符号引用来标识当前类加载器中的实际类,并返回对类实例的引用。
关于java - Java 中的符号引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17406159/