Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion on the checkcast bytecode instruction?

I'm working on my own implementation of the JVM and came around to the checkcast instruction. The full documentation is on this page. I'm curious because when enumerating the rules for how the cast works, one condition being checked is if the object reference being checked is of interface type. By my understanding, this shouldn't be possible; interfaces can't be directly instantiated, and any object that implements an interface has some other concrete class type. Am I missing something?

like image 565
templatetypedef Avatar asked Feb 10 '11 22:02

templatetypedef


1 Answers

It seems you were not the only one confused about this definition, this blog post has an explanation: http://mbravenboer.blogspot.com/2008/12/why-jvm-spec-defines-checkcast-for.html

It turns out that this is indeed an `impossible' case. The reason why this item is in the specification, is because checkcast is recursively defined for arrays:

  • If S is a class representing the array type SC[], that is, an array of components of type SC, then:
  • ...
  • If T is an array type TC[], that is, an array of components of type TC, then one of the following must be true:
    • ...
    • TC and SC are reference types, and type SC can be cast to TC by recursive application of these rules.

So, if you have an object of type List[] that is cast to an Collection[], then the rules for checkcast get recursively invoked for the types S = List and T = Collection. Notice that List is an interface, but an object can have type List[] at run-time. If have not verified this with the JVM Spec maintainers, but as far as I can see, this is the only reason why the rule for interface types is there.

like image 92
Jörn Horstmann Avatar answered Oct 31 '22 05:10

Jörn Horstmann