Java Class getTypeParameters()方法及示例

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

Java Class getTypeParameters()方法及示例

java.lang.Class类getTypeParameters() 方法是用来获取这个实体的类型参数。这个实体可以是一个类,一个数组,一个接口,等等。该方法返回一个代表类型变量的TypeVariable对象的数组。

语法:

public TypeVariable<Class<T>> getTypeParameters()

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

返回值: 该方法返回一个代表类型变量 的TypeVariable 对象 数组

下面的程序演示了getTypeParameters()方法。

示例1:

// Java program to demonstrate getTypeParameters() method import java.util.*; public class Test {    public static void main(String[] args)        throws ClassNotFoundException    {         // returns the Class object for this class        Class myClass = Class.forName("Test");         System.out.println("Class represented by myClass: "                           + myClass.toString());         // Get the type parameters of myClass        // using getTypeParameters() method        System.out.println(            "TypeParameters of myClass: "            + Arrays.toString(                  myClass.getTypeParameters()));    }}

输出

Class represented by myClass: class TestTypeParameters of myClass: []

例2:

// Java program to demonstrate getTypeParameters() method import java.util.*; public class Test {     public static void main(String[] args)        throws ClassNotFoundException    {        // returns the Class object for this class        Class myClass = Class.forName("java.lang.Integer");         System.out.println("Class represented by myClass: "                           + myClass.toString());         // Get the type parameters of myClass        // using getTypeParameters() method        System.out.println(            "TypeParameters of myClass: "            + Arrays.toString(                  myClass.getTypeParameters()));    }}

输出

Class represented by myClass: class java.lang.IntegerTypeParameters of myClass: []

参考资料: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getTypeParameters-

相关推荐