kaqqao kaqqao - 1 year ago 46
Java Question

How to get Class<T> from List<T>

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();


  1. Found this nice explanation of what erasure of the static type means.

  2. 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.

  3. Here's a great article on extracting generic types reflectively and a nice lib simplifying it

Answer Source

The erasure of the static type of items.get(0) is Object (since T is erased during compilation).

Therefore items.get(0).getClass() returns a Class<? extends Object>, not a Class<? extends T>, which explains why your attempted assignment fails.

This will pass compilation :

Class<? extends Object> clazz = items.get(0).getClass();

If you want the Class of the generic parameter to be known by that method, you can pass it as an additional argument.

void doSomething(List<T> items, Class<T> clazz) {