Video in progress
How do the invokestatic, invokespecial, invokevirtual, invokeinterface and invokedynamic instructions differ?
The first four differ in how they pick the method to call: static, exact (private/constructor/super), virtual dispatch and dispatch through an interface. invokedynamic binds the call site at runtime through a bootstrap method.
📖 Answer
Open any class with javap -c and you will see all five.
| Instruction | When | How the method is chosen |
|---|---|---|
invokestatic |
static method | exact at compile time |
invokespecial |
constructor, private (up to Java 11), super.foo() |
exact, overriding is not considered |
invokevirtual |
ordinary instance method through a class | by the object's actual class (vtable) |
invokeinterface |
through a reference of an interface type | by the actual class, itable lookup |
invokedynamic |
lambda, string concat, a record's toString/equals |
on the first call the bootstrap method returns a CallSite |
One note: starting with Java 11 (nestmates), private methods within a class are often called with invokevirtual.
What is this good for in practice? For the JIT, invokestatic and invokespecial are the easiest: the target is known and can be inlined right away. For invokevirtual/invokeinterface the JIT collects a profile: if only one class ever shows up at the call site, it inlines it anyway and adds a small check. So the claim "interfaces are slow" is almost never true on a modern JVM.
invokedynamic was added in Java 7 for dynamic languages, and since Java 8 it has been the main mechanism for lambdas.
Sign up to mark studied questions and save your progress.