I noticed something while I was derping around with generics. In the example below, doStuff1
compiles but doStuff2
doesn't:
public <T extends Foo> void doStuff1(T value) {
Class<? extends Foo> theClass = value.getClass();
}
public <T extends Foo> void doStuff2(T value) {
Class<? extends T> theClass = value.getClass();
}
So, I looked up the documentation for Object.getClass()
and found this:
The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called.
This made me a bit curious. Why is getClass()
designed this way? I can understand converting types to their raw classes if applicable, but I see no obvious reason why they'd necessarily have to make it also kill off T
. Is there a specific reason why it also gets rid of it, or is it just a general "let's just get rid of everything because it's easier; who would ever need it anyway" approach?
Object
and looking at the search rules; this is probably an artifact of how the JVM does its sorta-staticky magic to reflect on the object's runtime class. – Oates