How to Get class of Elements that List Contains?

前端 未结 4 381
醉梦人生
醉梦人生 2021-01-18 01:47

I have a list like that:

private List myList = new ArrayList();

I want to get the .class of T. How can I do that?

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-18 02:16

    This is only possible if the list, as implied in your example, is a field AND the type parameter is concrete rather than itself being a type parameter of the enclosing class (which seems to be the case in your example), and you can only get the declared type parameter for the field via reflection:

    Field listField = Test.class.getDeclaredField("myList");
    ParameterizedType listType= (ParameterizedType) listField.getGenericType();
    Class contentClass = (Class) listType.getActualTypeArguments()[0];
    

    Not sure if this is entirely correct, but you get the idea - it's rather complex because type parameters can be bounded and wildcards.

提交回复
热议问题