0

Why is the below cast possible without runtime error (i.e. ClassCastException)?

import java.lang.reflect.Type;
public class Demo {

    public static void main(String[] args) {
        Type t = Example.class;
        Class<Demo> demo = (Class<Demo>) t;
        System.out.println(demo);
    }
}

Console:

class Example

.

public class Example {

}
etxalpo
  • 1,146
  • 1
  • 14
  • 25
  • 3
    You aren't really casting here, just changing the template type – hd1 Apr 26 '14 at 22:34
  • What does template type mean in this context? – etxalpo Apr 26 '14 at 22:37
  • 4
    Two words: Type erasure. At runtime it's *really* `Class demo = (Class) t;` – Brian Roach Apr 26 '14 at 22:40
  • 2
    Note that it *should* be giving you a *compile* warning about an unchecked cast, which would help explain why the cast does not fail at runtime (because it's unchecked!). – Mark Peters Apr 26 '14 at 22:41
  • @BrianRoach you should write that as an answer, so that etxalpo can accept it, and so that I can upvote it. – Dawood ibn Kareem Apr 26 '14 at 22:59
  • @DavidWallace Honestly, there's a little more to it in terms of how casting works in Java and ... I need to run out to the grocery store. There's *got* to be a dup somewhere, I would imagine. – Brian Roach Apr 26 '14 at 23:01
  • class foo – hd1 Apr 26 '14 at 23:34
  • Found it. Possible duplicate of [Why does it compile when casting to an unrelated interface?](http://stackoverflow.com/questions/19824941/why-does-it-compile-when-casting-to-an-unrelated-interface) - the answer that quotes the JLS in particular – Brian Roach Apr 27 '14 at 01:40

0 Answers0