Stas
Stas

Reputation: 103

get class from java.util.List<SomeType>

how to get class from this expression java.util.List

Upvotes: 8

Views: 13783

Answers (3)

CodeMonkey
CodeMonkey

Reputation: 12444

You can try something like this:

Class<List<Foo>> cls = (Class<List<Foo>>)(Object)List.class

Upvotes: 0

Bozho
Bozho

Reputation: 597432

If your List is defined with a concrete type param, like for example:

private class Test {
   private List<String> list;
}

then you can get it via reflection:

Type type = ((ParameterizedType) Test.class.getDeclaredField("list")
     .getGenericType()).getActualTypeArguments()[0];

However, if the type is not known at compile time, it is lost due to type erasure

Upvotes: 7

DJClayworth
DJClayworth

Reputation: 26916

I assume you want to know the template class of the List at run time, and the short answer is: you can't. Java generics are used only at compile time: the template arguments are erased before byte code is generated. This is called "type erasure".

Upvotes: 6

Related Questions