Clashsoft
Clashsoft

Reputation: 11882

Java Bytecode invokeinterface instruction

Looking at this Java Bytecode (from the Eclipse ClassFile viewer), I noticed something strange with the invokeinterface instruction: It has a nargs (number of arguments) 'attribute' that occupies 2 bytes:

35  aload_2 [map]
36  ldc <String "a"> [15]
38  invokeinterface java.util.Map.get(java.lang.Object) : java.lang.Object [33] [nargs: 2]
43  checkcast java.lang.String [35]
46  invokevirtual java.io.PrintStream.println(java.lang.Object) : void [47]
49  getstatic java.lang.System.out : java.io.PrintStream [41]

Why does this exist? What is the difference between invokeinterface and invokevirtual? Shouldn't the JVM be able to infer the number of arguments (thus the number of values to pop from the stack) from the given method signature?

Upvotes: 1

Views: 1136

Answers (1)

yole
yole

Reputation: 97148

You're right that the number of arguments can be inferred from the signature. The JVM spec has this to say about that:

"The count operand of the invokeinterface instruction records a measure of the number of argument values, where an argument value of type long or type double contributes two units to the count value and an argument of any other type contributes one unit. This information can also be derived from the descriptor of the selected method. The redundancy is historical."

Upvotes: 7

Related Questions