Determine if object is of given type
Bytecode
Type | Description |
u1 | instanceof opcode = 0xC1 (193) |
u2 | index |
Stack
..., objectref => ..., result
The instanceof instruction is used to implement the Java language's instanceof operator, which tests whether an object reference or array belongs to a given class.
instanceof takes a single parameter, <type>. <type> is either the name of a Java class, or it is the type descriptor of an array.
At runtime, <type> is resolved. Next, instanceof pops objectref (a reference to an object) off the top of the operand stack. If objectref is an instance of <type> or one of <type>'s subclasses, the int 1 is pushed onto the stack, otherwise the int 0 is pushed onto the stack. If objectref is null, the result is always 0. If <type> is an interface, int-result will be 1 if objectref implements that interface, and 0 if objectref does not implement the interface.
The objectref, which must be of type reference
,
is popped from the operand stack. If objectref is not null
and is an instance of the resolved class, array, or interface, the instanceof
instruction pushes an int
result of 1 as an int on the operand
stack. Otherwise, it pushes an int
result of 0.
Example
; using instanceof to test for a String: aload_1 ; push object reference in local variable 1 onto stack instanceof java/lang/String; ; test if item on stack is a String ifne HaveString ; if so, goto HaveString return ; otherwise, return HaveString: ; if this point is reached, local variable 1 holds a string ; this example uses instanceof to test if local variable 1 holds ; an integer array aload_1 ; push local variable 1 onto the stack instanceof [I ; test if the top item on the stack is an integer array ifne HaveIntegerArray ; if so, jump to HaveIntegerArray return ; simply return if local variable 1 is not an int array HaveIntegerArray: ; if this point is reached, local variable 1 holds an integer array ; you can also use instanceof to test that objects implement a given interface, ; e.g. aload_1 ; push local variable 1 onto the stack instanceof java/lang/Runnable ; test if it implements the Runnable interface ifne HaveARunnable ; if so, jump to HaveARunnable return ; otherwise return HaveARunnable: ; if this point is reached, local variable 1 holds a reference to an object ; that implements the Runnable interface.
Notes
The instanceof instruction is fundamentally very similar to
the checkcast instruction. It differs in its treatment of null
, its
behavior when its test fails (checkcast throws an exception, instanceof
pushes a result code), and its effect on the operand stack.