Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symbolic references in Java

In these days I have been playing with Java reflection and .class format. I'm currently studying ldc instruction.

In JVM Specification I found term I don't understand: symbolic reference, and I have the following questions.

  1. What does it mean?

  2. Where is it used?

  3. In which cases does the ldc instruction load a symbolic reference?
  4. Is there any code in Java corresponding to that action?
like image 404
user35443 Avatar asked Jul 01 '13 13:07

user35443


People also ask

What is symbolic reference?

Symbolic reference thus exists between a sound-word (or other material instantiation of a signifier) appearing in the occasion and its occurrence in a preceding occasion.

What is direct references in Java?

A direct reference to a type can simply point to the implementation-specific data structure in the method area that holds the type data. A direct reference to a class variable can point to the class variable's value stored in the method area.


1 Answers

It would be helpful if you would quote the exact piece of the documentation that's giving you trouble. Since you haven't, I'm going to take a guess at what you might have quoted, from the doc for 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). ...

This quote has a link to another section of the JVM spec (5.1), which describes the run-time constant pool:

a run-time data structure that serves many of the purposes of the symbol table of a conventional programming language implementation

What this means is that the run-time constant pool contains information about the pieces of a class in symbolic form: as text values.

So, when ldc is given a "symbolic reference" to a class, it's given the index of a CONSTANT_Class_info structure within the constant pool. If you look at the definition of this structure, you'll see that it contains a reference to the name of the class, also held within the constant pool.

TL;DR: "symbolic references" are strings that can be used to retrieve the actual object.


An example:

if (obj.getClass() == String.class) {
    // do something
}

Becomes the following bytecode:

aload_1
invokevirtual   #21; //Method java/lang/Object.getClass:()Ljava/lang/Class;
ldc     #25; //class java/lang/String
if_acmpne       20

In this case, the ldc operation refers to a class that is stored symbolically. When the JVM executes this opcode, it will use the symbolic reference to identify the actual class within the current classloader, and return a reference to the class instance.

like image 50
parsifal Avatar answered Sep 23 '22 02:09

parsifal