checkcast <type><type> is the name of a Java class or interface (e.g. java/lang/String), or the type descriptor of an array (e.g. [[Ljava/lang/String;).
Stack Before
Description After objectref objectref ... ...
checkcast checks that the top item on the operand stack (a reference to an object or array) can be cast to a given type. For example, if you write in Java:
return ((String)obj);then the Java compiler will generate something like:
aload_1 ; push -obj- onto the stack checkcast java/lang/String ; check its a String areturn ; return itcheckcast is actually a shortand for writing Java code like:
if (! (obj == null || obj instanceof <class>)) { throw new ClassCastException(); } // if this point is reached, then object is either null, or an instance of // <class> or one of its superclasses.In Jasmin, checkcast takes a single parameter, <type>. <type> is either the name of a Java class or interface, or it is the type descriptor of an array. At runtime, the symbolic name given by <type> is resolved to a Java class (see Chapter 7 for a description of how classes are resolved). Next, checkcast examines the top item on the stack. If objectref belongs to <type> (or one of its subclasses), or if it is null, the objectref is left on the stack and execution continues at the subsequent instruction. If not, a ClassCastException is thrown.
Example
; push object in local variable 1 onto stack aload_1 ; check if it is an instance of Throwable or one of its subclasses. checkcast java/lang/Throwable ; if execution reaches here, the object in local variable 1 ; is still on the stack, and is either null or a Throwable object.
; --- ; Note that checkcast can also be used to check that an array belongs to a given type, ; e.g. to check that local variable 1 contains an array of Strings, use: aload_1 checkcast [Ljava/lang/String; ; if execution reaches here, the object on the stack is an array of Strings, or it is null.Exceptions
ClassCastException - the object on the stack is not an instance of the specified class
Bytecode
In bytecode, immediately following the checkcast 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 | checkcast opcode = 0xC0 (192) |
u2 | index |
instanceof