Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do DUP when creating new instance

Tags:

java

bytecode

Currently I'm just in a project which uses java bytecode. I usually see that when creating a new class instance and invoke a method on it, the bytecode will be like:

NEW <MyClass>
DUP
INVOKESPECIAL <MyClass.<init>>

Here why should do "DUP"? From VM Spec, I get the description "Duplicate the top value on the operand stack and push the duplicated value onto the operand stack". But why duplicating the top value on the operand stack is necessary here? Thanks.

like image 397
Eric Jiang Avatar asked Sep 02 '11 11:09

Eric Jiang


1 Answers

Because INVOKESPECIAL will consume value created by NEW from the operand stack, but you may need to actually use this value, so the reference is duplicated in advance.

like image 84
Eugene Kuleshov Avatar answered Sep 30 '22 21:09

Eugene Kuleshov