Artem
Artem

Reputation: 119

How does getting field or method by name works in Java?

I am new to Java and some things are not clear to me. For instance, in C++ if we have

    class A {
        int field1;
        int field2;
        void method() { }
    } a;

and we use a.field1 or a.method(), compiler already knows where they are stored in memory relatively to a. But Java has .class files which have the information about fields and methods with their names so that it doesn't matter where they are stored in memory for ones who use those fields and methods. Does it mean that when we do a.field1 in Java, JVM first figures out where this field has to be in memory relatively to a and then gets this field or does it change all a.field1 to *(a + offset of field1), a.field2 to *(a + offset of field2) etc on startup?

Upvotes: 2

Views: 125

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074475

The situation is essentially the same in Java as it is in C++: The JVM knows where the fields are within the object.

If you want all the gory details, you can read up on it in the JVM specification, in particular the getfield bytecode, which says amongst other things:

The objectref, which must be of type reference, is popped from the operand stack. The unsigned indexbyte1 and indexbyte2 are used to construct an index into the run-time constant pool of the current class (§2.6), where the value of the index is (indexbyte1 << 8) | indexbyte2. The run-time constant pool item at that index must be a symbolic reference to a field (§5.1), which gives the name and descriptor of the field as well as a symbolic reference to the class in which the field is to be found. The referenced field is resolved (§5.4.3.2). The value of the referenced field in objectref is fetched and pushed onto the operand stack.

The type of objectref must not be an array type. If the field is protected, and it is a member of a superclass of the current class, and the field is not declared in the same run-time package (§5.3) as the current class, then the class of objectref must be either the current class or a subclass of the current class.

Upvotes: 2

Related Questions