鍍金池/ 問答/Java  網(wǎng)絡(luò)安全/ JAVA如何在類中使用ParameterizedType獲取泛式類型

JAVA如何在類中使用ParameterizedType獲取泛式類型

在類中使用ParameterizedType獲取類的實體類的泛式類
有以下代碼:

public class Demo<T> {
    
    private Class<T> clazz;
    
    public T getDemo() throws InstantiationException, IllegalAccessException{
        return clazz.newInstance();
    }

    public static void test() throws InstantiationException, IllegalAccessException{
        String str = new Demo<String>().getDemo();
    }
    
}

現(xiàn)在我要調(diào)用test()方法,獲取一個String實體類,但當我調(diào)用的時候會拋出NullPointerException指clazz為空值,無法調(diào)用。那么這時候我改一下getDemo方法,使用ParameterizedType獲取泛式并且賦值

    public T getDemo() throws InstantiationException, IllegalAccessException{
        Type superClass = getClass();
        if(superClass instanceof ParameterizedType){
            Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
            this.clazz = (Class<T>) type;
        }else{
            System.out.println("不相等");
        }
        return clazz.newInstance();
    }

但是這時候獲取到的superClass為 Demo ,并不是 Demo<String>,因此superClass instanceof ParameterizedType不成立,控制臺輸出"不相等",clazz仍未null,所以想問一下大家這種情況下要怎么樣才能獲取到泛型的類呢?

注意就算把Type superClass = getClass();改為 Type superClass = getClass().getGenericSuperclass(); 也是沒有用的,因為Demo類不繼承其他類,所以獲取到的是Object,也是不相等的。

回答
編輯回答
妖妖

創(chuàng)建一個類繼承Demo<T>,使用

 Type superClass = getClass().getGenericSuperclass();
 Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0];

得到泛型類型。

2017年10月20日 05:26