简体   繁体   中英

how does bytecode represent another class

If I have these files:

//Gizmo.java
public class Gizmo {
    public static void main(String[] args) {
        Gadget g = new Gadget();
    }
}

.

//Gadget.java
public class Gadget {
    public static void main(String[] args) {
        System.out.println("hello world");
    }
}

And I compile them both with javac Gizmo.java Gadget.java , then I have a question. How does the Gizmo.class file reference the "Gadget" class? Is there simply a string "Gadget" somewhere in the file?

As the comments mentioned, you can find the exact definition of the format here: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.2

The long and short of it (from my understanding) is that there is a UTF-8 string which states the name of the class being referenced, and then I am guessing that there is either a) an arbitrary number associated with it or b) the address of that string is used so that the rest of the binary class file simply uses that number to reference the class.

For example, if you compile the example code in the question and then open up Gizmo.class with a text editor, you will see the string "Gadget" in there.

Your answer lies in following line of JLS4.2.1 which says that:

Class and interface names that appear in class file structures are always represented in a fully qualified form known as binary names (JLS §13.1). Such names are always represented as CONSTANT_Utf8_info structures (§4.4.7) and thus may be drawn, where not further constrained, from the entire Unicode codespace. Class and interface names are referenced from those CONSTANT_NameAndType_info structures (§4.4.6) which have such names as part of their descriptor (§4.3), and from all CONSTANT_Class_info structures (§4.4.1).

For historical reasons, the syntax of binary names that appear in class file structures differs from the syntax of binary names documented in JLS §13.1. In this internal form, the ASCII periods (.) that normally separate the identifiers which make up the binary name are replaced by ASCII forward slashes (/). The identifiers themselves must be unqualified names (§4.2.2).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM