Invisible java bytecode lines

I am wondering why Java Bytecode string lines are not sequential.

What happens, for example, in (not listed) lines 2 and 3 of the next getter?

public java.lang.String getX(); Code: 0: aload_0 1: getfield #2; //Field x:Ljava/lang/String; 4: areturn 

I use the ASM framework for working with bytecode. When I visit the code of a method using the tree API, I also get these "hidden" instructions (but with an operation code of -1). I would like to know what they are for.

+4
source share
2 answers

I don't think 0, 1, 4 are linenumbers, but byte offsets in bytecode.

  • aload_0 - one byte
  • getfield - three bytes (one operation code, one "arg" index with two bytes "
  • areturn - one byte

So 2 and 3 are just part of the getfield operation.

+8
source

Little explanation

The size of the array of local variables is determined at compile time and depends on the number and size of local variables and the parameters of the formal method. The operand stack is the LIFO stack used to enter and extrude values. Its size is also determined at compile time. Some instruction instructions push values ​​onto the operand stack; others take operands from the stack, manipulate them and push the result. The operand stack is also used to get return values ​​from methods.

 public String getBar(){ return bar; } public java.lang.String getBar(); Code: 0: aload_0 1: getfield #2; //Field bar:Ljava/lang/String; 4: areturn 

The bytecode for the method described above consists of three instructions for the operation code. The first operation code aload_0 pops the value from index 0 of the local variable table onto the operand stack. This reference is always stored at location 0 of the local variable table for instance constructors and methods. The next opcode command, getfield, is used to retrieve a field from an object. The last command, isturn, returns the link from the method.

Each method has a corresponding bytecode. After looking at the .class file with a hex editor, you will see the following values ​​in the bytecode array:

However, the bytecode for the getBar method is 2A B4 00 02 B0. Code 2A corresponds to the command aload_0, and B0 corresponds to isturn. It may seem strange that the method bytecode has 3 commands, but the byte array contains 5 elements. This is due to the fact that 2 parameters (00 02) are required in the getfield (B4) field, and these parameters occupy positions 2 and 3 in the array, therefore the size of the array is 5, and the retraction instruction is shifted to position 4.

A source

Java bytecode instruction lists

+4
source

All Articles