獲取在接口或者類上定義的泛型類型


通過Class類上的 getGenericSuperclass() 或者 getGenericInterfaces() 獲取父類或者接口的類型,然后通過ParameterizedType.getActualTypeArguments()

可以得到定義在類或者接口上的泛型類型,具體參考如下代碼:

package com.jiaoyiping.event;
 /*
  * Created with Intellij IDEA
  * USER: 焦一平
  * Mail: jiaoyiping@gmail.com
  * Date: 2016/12/4
  * Time: 9:28
  * To change this template use File | Settings | Editor | File and Code Templates
 */

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class GenericTypeTest {
    static class Test1 extends T<Person, Animal> {

    }

    static class Test2 implements I<Person, Animal>, I2<Fruit> {
    }

    public static void main(String[] args) {
        //獲取類定義上的泛型類型
        Test1 test1 = new Test1();
        Type types = test1.getClass().getGenericSuperclass();

        Type[] genericType = ((ParameterizedType) types).getActualTypeArguments();
        for (Type t : genericType) {
            System.out.println(t.getTypeName());
        }
        System.out.println("===============================================");

        //獲取接口定義上的泛型類型
        Test2 test2 = new Test2();
        //一個類可能實現多個接口,每個接口上定義的泛型類型都可取到
        Type[] interfacesTypes = test2.getClass().getGenericInterfaces();
        for (Type t : interfacesTypes) {
            Type[] genericType2 = ((ParameterizedType) t).getActualTypeArguments();
            for (Type t2 : genericType2) {
                System.out.println(t2.getTypeName());
            }
        }


    }
}

class T<T1, T2> {
    public void printT(T1 t1, T2 t2) {
        System.out.println(t1.getClass());
        System.out.println(t2.getClass());
    }
}

interface I<T1, T2> {
}

interface I2<K> {

}

class Person {
    @Override
    public String toString() {
        return "Person Type";
    }
}

class Animal {
    @Override
    public String toString() {
        return "Animal Type";
    }
}

class Fruit {
    @Override
    public String toString() {
        return "Fruit Type";
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM