3

When I compile this simple code

class Main {
    public void execute() {    }

    public static void main(String[] args) {
        Runnable run = new Main()::execute;
    }
}

I get the following byte code for the main method:

 0  new user.Main [2]
 3  dup
 4  invokespecial user.Main() [3]
 7  dup
 8  invokevirtual java.lang.Object.getClass() : java.lang.Class [4] // <--- ???
11  pop
12  invokedynamic 0 run(user.Main) : java.lang.Runnable [5]
17  astore_1 [run]
18  return

I'm wondering why the compiler decided to emit an invokevirtual java.lang.Object.getClass() followed directly by a pop. What's the purpose of this seemingly useless call?

WorldSEnder
  • 4,875
  • 2
  • 28
  • 64
  • 2
    You can find useful information [here](http://stackoverflow.com/questions/13115812/why-bytecode-calls-object-getclass-at-a-direct-field-access) – Fady Saad Apr 14 '17 at 02:50
  • This is an interesting example of a naive compiler implementation. It emits the code of the `new …` expression, followed by code ensuring that the captured reference of the `expression::name` construct is not `null` (as mandated), but doesn’t consider that this is entirely obsolete in this special case, as the result of `new …` can never be `null`. – Holger Apr 19 '17 at 17:49

0 Answers0