invokevirtual dispatches a Java method. It is used in Java to
invoke all methods except interface methods (which use
invokeinterface), static methods (which use invokestatic),
and the few special cases handled by invokespecial.
For example, when you write in Java:
Object x;
...
x.equals("hello");
this
is compiled into something like:
aload_1 ; push local variable 1 (i.e. 'x') onto stack
ldc "hello" ; push the string "hello" onto stack
; invoke the equals method
invokevirtual java/lang/Object/equals(Ljava/lang/Object;)Z
; the boolean result is now on the stack
Note
that the actual method run depends on the runtime type of the object
invokevirtual is used with. So in the example above, if x is an
instance of a class that overrides Object's equal method, then the subclasses'
overridden version of the equals method will be used.
Before performing the method invokation, the class and the method identified by
<method-spec> are resolved. See Chapter 9 for a description of how
methods are resolved.
invokevirtual looks at the descriptor given in
<method-spec>, and determines how many arguments the method takes (this
may be zero). It pops these arguments off the operand stack. Next it pops
objectref off the stack. objectref is a reference to the object
whose method is being called. invokevirtual retrieves the Java class
for objectref, and searches the list of methods defined by that class
and then its superclasses, looking for a method called methodname, whose
descriptor is descriptor.
Once a method has been located, invokevirtual calls the method. First,
if the method is marked as synchronized, the monitor associated with
objectref is entered. Next, a new stack frame structure is established
on the call stack. Then the arguments for the method (which were popped off the
current method's operand stack) are placed in local variables of the new stack
frame structure. arg1 is stored in local variable 1, arg2 is stored in local
variable 2 and so on. objectref is stored in local variable 0 (the local
variable used for the special Java variable this). Finally, execution
continues at the first instruction in the bytecode of the new method.
When the method called by invokevirtual returns, any single (or
double) word return result is placed on the operand stack of the
current method and execution continues at the instruction that follows
invokevirtual in the bytecode.