Get type of a generic parameter in Java with reflection

后端 未结 18 1979
死守一世寂寞
死守一世寂寞 2020-11-22 05:56

Is it possible to get the type of a generic parameter?

An example:

public final class Voodoo {
    public static void chill(List aListWithTy         


        
18条回答
  •  被撕碎了的回忆
    2020-11-22 06:13

    Actually I got this to work. Consider the following snippet:

    Method m;
    Type[] genericParameterTypes = m.getGenericParameterTypes();
    for (int i = 0; i < genericParameterTypes.length; i++) {
         if( genericParameterTypes[i] instanceof ParameterizedType ) {
                    Type[] parameters = ((ParameterizedType)genericParameterTypes[i]).getActualTypeArguments();
    //parameters[0] contains java.lang.String for method like "method(List value)"
    
         }
     }
    

    I'm using jdk 1.6

提交回复
热议问题