开发者

get class from java.util.List<SomeType>

开发者 https://www.devze.com 2023-01-08 20:44 出处:网络
how开发者_运维百科 to get class from this expression java.util.ListIf your List is defined with a concrete type param, like for example:

how开发者_运维百科 to get class from this expression java.util.List


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


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


You can try something like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消