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?
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.
If S is an interface type, then:
If T is a class type, then T must be Object (§2.4.7).
If T is an interface type, then T must be the same interface as S or a superinterface of S (§2.13.2).
That seems clear to me : an interface can be cast to an interface that it extended. This case is used for example when you call serialization on DataInputStream : the interface DataInputStream implements Serializable, so we cast the object to Serializable without even knowing what is the object's implemented class.
精彩评论