Java Class getTypeParameters()方法及示例

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 Test
TypeParameters 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.Integer
TypeParameters of myClass: []

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程