Java源码解析(附录)(3) —— GenericDeclaration

GenericDeclaration

可以声明类型变量的实体的公共接口,也就是说,只有实现了该接口才能在对应的实体上声明(定义)类型变量,这些实体目前只有三个:Class(类)、Construstor(构造器)、Method(方法)(详见:TypeVariable —— 类型变量)。

源码

public interface GenericDeclaration {
    //获得声明列表上的类型变量数组
    public TypeVariable<?>[] getTypeParameters();
}

概述

所有可以声明/定义类型变量(TypeVariable)的实体的公共父接口,其直接实现子类:java.lang.reflect子包中的:Class,Method,Constructor,所以,这三个对应的类上、方法上、构造器上可以声明(定义)类型变量,GenericDeclaration的直接实现子类没有Field类,所以属性上面不能定义类型变量。

源码详解

1.getTypeParameters
返回实体上声明(定义)的所有的类型变量。

public class Main<K extends classA & interfaceB, V> {
    classA<K>[][] key;
    V value;
    public static void main(String[] args) throws Exception
    {
        TypeVariable[] types = Main.class.getTypeParameters();
        for(TypeVariable type : types){
            System.out.println(type.getName());
        }

    }
}
//输出结果
K
V

猜你喜欢

转载自blog.csdn.net/a327369238/article/details/52710827