Get type of a generic parameter in Java with reflection

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

    Just for me reading this snippet of code was hard, I just divided it into 2 readable lines :

    // assuming that the Generic Type parameter is of type "T"
    ParameterizedType p = (ParameterizedType) getClass().getGenericSuperclass();
    Class c =(Class)p.getActualTypeArguments()[0];
    

    I wanted to create an instance of the Type parameter without having any parameters to my method :

    publc T getNewTypeInstance(){
        ParameterizedType p = (ParameterizedType) getClass().getGenericSuperclass();
        Class c =(Class)p.getActualTypeArguments()[0];
    
        // for me i wanted to get the type to create an instance
        // from the no-args default constructor
        T t = null;
        try{
            t = c.newInstance();
        }catch(Exception e){
            // no default constructor available
        }
        return t;
    }
    

提交回复
热议问题