checkcast : ensure type of an object or array : index : visitTypeInsn()
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.; 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.
| Before | After |
| objectref | objectref |
| ... | ... |
| Type | Description |
| u1 | checkcast opcode = 0xC0 (192) |
| u2 | index |