This is ok:
Class<? extends String> stringClass = "a".getClass();
But this gets error:
<T> void f(T obj) {
Class<? extends T> objClass = obj.getClass();
}
I know I can cast it like:
<T> void f(T obj) {
@SuppressWarnings("unchecked")
Class<? extends T> objClass = (Class<? extends T>) obj.getClass();
}
But why the previous error? Will the next release of Java 7 will support such usage?
EDIT
I have no problem dealing with type erasure, and just put the extra SuppressWarnings
whenever my code is right but the compiler just doesn't support of it.
The question behind is, SuppressWarnings
is just not enough. When T.getClass() => ? extends T
is obviously intuitive, why should I have to suppress any warning?
As you have already seen in the javadoc:
The actual result type is Class where |X| is the erasure of the static type of the expression on which getClass is called.
The Object.getClass()
is a special case when we talk about Java generics. It's different to the declared form, which just returns Classs<?>
. I don't know how IDE like Eclipse stuff is implemented, in Eclipse IDE, the completion will generate Class<? extends |X|>
instead of Class<?>
for you. I guess there maybe some magic stuff in the Object class, to make the base type, which ? extends from, be different between derived types. So, it's just not possible to write your own Object class in Java language, which will return something like ? extends |X|
where |X|
is this.getClass()
. But the Java Object
does, because it's a special case.