instanceof : test class of object : index : visitTypeInsn()

Description
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.
See also
checkcast
Stack
Before After
objectref int-result
... ...
Bytecode
Type Description
u1 instanceof opcode = 0xC1 (193)
u2 index