Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why invokeSpecial is needed when invokeVirtual exists

Tags:

java

jvm

bytecode

There are three opcodes to invoke Java methods. It is clear that invokeStatic is just for static method invocation.

As far as I know invokespecial is used when invoking constructor and private methods. So, do we need to differenticate private and public method invocation at run time? It could be invoked with same opcode say invokevirtual?

Does JVM deals with private and public method definition? As far as I know public and private keywords is just needed at development phase for encapsulation?

like image 611
Ahmet Karakaya Avatar asked Dec 07 '12 13:12

Ahmet Karakaya


People also ask

What is invokevirtual?

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.

How the Java virtual machine handles method invocation and return?

When the JVM invokes a method, it creates a stack frame of the proper size for that method. Adding a new frame onto the Java stack when a method is invoked is called "pushing" a stack frame; removing a frame when a method returns is called "popping" a stack frame. The Java stack is made up solely of these frames.

What is Invokedynamic?

A: invokedynamic is a bytecode instruction that facilitates the implementation of dynamic languages (for the JVM) through dynamic method invocation. This instruction is described in the Java SE 7 Edition of the JVM Specification.


1 Answers

From this site

The answer can be easily found if one reads the Java VM Spec carefully:

The difference between the invokespecial and the invokevirtual instructions is that invokevirtual invokes a method based on the class of the object. The invokespecial instruction is used to invoke instance initialization methods as well as private methods and methods of a superclass of the current class.

In other words, invokespecial is used to call methods without concern for dynamic binding, in order to invoke the particular class’ version of a method.

like image 69
Tim Pote Avatar answered Oct 04 '22 20:10

Tim Pote