I feel utterly silly for having to ask this, but I'm failing to understand why doesn't the following Java code compile:
void <T> doSomething(List<T> items) {
Class<? extends T> clazz = items.get(0).getClass();
...
}
From Java doc:
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. For example, no cast is required in this code fragment:
Number n = 0; Class< ? extends Number> c = n.getClass();
EDIT:
Found this nice explanation of what erasure of the static type means.
There's a way to preserve generic type information using subclasses, known as super type token. A now deleted answer helpfully pointed out that Guava library has a convenient utility for exploiting this.
Here's a great article on extracting generic types reflectively and a nice lib, called GenTyRef, simplifying it
I forked GenTyRef to add support for working with
AnnotatedType
s (introduced in Java 8). It's called GeantyRef (and it's in Maven Central)
>`.