Get type of a generic parameter in Java with reflection

后端 未结 18 1958
死守一世寂寞
死守一世寂寞 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:12

    You cannot get a generic parameter from a variable. But you can from a method or field declaration:

    Method method = getClass().getDeclaredMethod("chill", List.class);
    Type[] params = method.getGenericParameterTypes();
    ParameterizedType firstParam = (ParameterizedType) params[0];
    Type[] paramsOfFirstGeneric = firstParam.getActualTypeArguments();
    

提交回复
热议问题