instanceof <type><type> is the name of a Java class, e.g. java/lang/String. Alternatively, to test for array references, <type> can be the type descriptor of an array, e.g. [[Ljava/lang/String;
Stack Before
Description After objectref int-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 (Chapter 7 describes how classes are 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.
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.Bytecode
In bytecode, immediately following the instanceof opcode is a 16-bit unsigned short integer. This integer is the index of an entry in the constant pool of the current class. The entry is tagged a CONSTANT_Class entry. The name field of the CONSTANT_Class entry is the same as the string given by <type> parameter in Jasmin.
Type | Description |
u1 | instanceof opcode = 0xC1 (193) |
u2 | index |
checkcast
Chapter 7 gives a pseudo-code implementation of instanceof.