获取在接口或者类上定义的泛型类型

来源:互联网 发布:js 字段包含某些值 编辑:程序博客网 时间:2024/06/05 12:49

通过Class类上的 getGenericSuperclass() 或者 getGenericInterfaces() 获取父类或者接口的类型,然后通过ParameterizedType.getActualTypeArguments()

可以得到定义在类或者接口上的泛型类型,具体参考如下代码:

 /*  * 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";    }}

转自:https://www.cnblogs.com/jiaoyiping/p/6130355.html

原创粉丝点击