Reputation: 103
how to get class from this expression java.util.List
Upvotes: 8
Views: 13783
Reputation: 12444
You can try something like this:
Class<List<Foo>> cls = (Class<List<Foo>>)(Object)List.class
Upvotes: 0
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
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