|
|
|
Advertisement
|
Summary
This article takes a look at how method invocation and return is handled by the Java virtual machine, with a close inspection of the relevant bytecodes is included. The article ends with a source-code example of method invocation.
This month's Under The Hood focuses on method invocation and return inside the Java virtual machine (JVM). It describes the four ways Java (and native) methods can be invoked, gives a code sample that illustrates the four ways, and covers the relevant bytecodes.
Method invocation
The Java programming language provides two basic kinds of methods:
instance methods and class (or static) methods. The
difference between these two kinds of methods are:
Instance methods require an instance before they can
be invoked, whereas class methods do not.
Instance methods use dynamic (late) binding, whereas
class methods use static (early) binding.
When the Java virtual machine invokes a class method, it selects the method to invoke based on the type of the object reference, which is always known at compile-time. On the other hand, when the virtual machine invokes an instance method, it selects the method to invoke based on the actual class of the object, which may only be known at run time.
The JVM uses two different instructions, shown in the following
table, to invoke these two different kinds of methods: invokevirtual
for instance methods, and invokestatic for
class methods.
| Opcode | Operand(s) | Description |
|---|---|---|
invokevirtual |
indexbyte1, indexbyte2 |
pop objectref and args, invoke method at constant pool index |
invokestatic |
indexbyte1, indexbyte2 |
pop args, invoke static method at constant pool index |
|
Sponsored Links
|