Specifying generic collection type param at runtime (Java Reflection)

前端 未结 4 746
情书的邮戳
情书的邮戳 2021-01-06 02:40

I\'d like to get the generic type of a collection, using reflection, at runtime.

Code (JAVA):

Field collectionObject = object.getClass().getDeclaredF         


        
4条回答
  •  無奈伤痛
    2021-01-06 03:34

    Copied from my post at: https://stackoverflow.com/questions/1004022/java-generic-class-determine-type/1005283#1005283

    I've used a similar solution to what he explains here for a few projects and found it pretty useful.

    http://blog.xebia.com/2009/02/07/acessing-generic-types-at-runtime-in-java/

    The jist of it is using the following to determine the type parameter at runtime:

    public Class returnedClass {
      ParameterizedType parameterizedType =
        (ParameterizedType) getClass().getGenericSuperClass();
     return (Class) parameterizedtype.getActualTypeArguments()[0];
    }
    

提交回复
热议问题