Check whether object is of given type
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 |
Stack ..., 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 it
checkcast 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.
The objectref must be of type reference
.
The index is an index into the constant pool of the constant pool entry of reference to a class, array, or interface type.
If objectref is null
or can be cast to the
resolved class, array, or interface type, the operand stack is unchanged; otherwise, the checkcast
instruction throws a ClassCastException
.
The following rules are used to determine whether an objectref
that is not null
can be cast to the resolved type: if S is the class of the
object referred to by objectref and T is the resolved class, array, or interface
type, checkcast determines whether objectref can be cast to type T as
follows:
[]
, that is, an array of
components of type SC, then:
S cannot be an interface type, because there are no instances of interfaces, only instances of classes and arrays.
; 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
Notes
The checkcast instruction is very similar to the instanceof
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.