Java Constructor getTypeParameters()方法及示例

来源:这里教程网 时间:2026-02-17 20:44:11 作者:

Java Constructor getTypeParameters()方法及示例

构造函数 类的 getTypeParameters() 方法用于获取该构造函数对象所声明的TypeVariable对象的数组,按声明顺序排列。数组中的元素代表方法所声明的类型变量对象。如果Method对象的泛型声明不包含任何类型变量,那么这个getTypeParameters()方法将返回一个长度为0的数组。

语法

public TypeVariable<Constructor<T>>[] getTypeParameters()

参数: 该方法不接受任何参数。

返回值: 该方法返回一个 TypeVariable 对象 的数组 ,这些对象代表该泛型声明所声明的类型变量。

异常: 如果这个泛型声明的泛型签名不符合《Java™ 虚拟机规范》中规定的格式,该方法会抛出 GenericSignatureFormatError

下面的程序说明了 getTypeParameters() 方法。

程序 1 :

// Java program to demonstrate// Constructor.getTypeParameters() method  import java.lang.reflect.Constructor;import java.lang.reflect.TypeVariable;  public class GFG {      public static void main(String... args)        throws NoSuchMethodException    {          // Create Test class        Class<Test> cls = Test.class;          // Create Constructor Object        Constructor[] constructors            = cls.getConstructors();          // get Annotation array        TypeVariable[] typeVariables            = constructors[0].getTypeParameters();          System.out.println("TypeVariables:"                           + typeVariables);    }}class Test<N extends Number> {    public Test(N n) {}}

输出。

TypeVariables:[Ljava.lang.reflect.TypeVariable;@15db9742

程序2

// Java program to demonstrate// Constructor.getTypeParameters() method  import java.lang.reflect.TypeVariable;  public class GFG {      public static void main(String... args)    {          // get Type Parameters        TypeVariable<Class<GFG_Demo> >[] typeParameters            = GFG_Demo.class.getTypeParameters();          // print result        for (TypeVariable<Class<GFG_Demo> >                 typeParameter : typeParameters) {            System.out.println(typeParameter);        }    }      private static class GFG_Demo<N, E> {    }}

输出。

NE

参考文献: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Constructor.html#getTypeParameters()

相关推荐