📜  Java中的类 getGenericSuperclass() 方法和示例

📅  最后修改于: 2022-05-13 01:54:21.638000             🧑  作者: Mango

Java中的类 getGenericSuperclass() 方法和示例

Java.lang.Class 类getGenericSuperclass()方法用于获取该实体的超类的类型。这个实体可以是一个类、一个数组、一个接口等。该方法返回这个实体的超类的类型。
句法:

public Type getGenericSuperclass()

参数:此方法不接受任何参数。
返回值:该方法返回该实体的超类的类型
异常:此方法引发以下异常:

  • GenericSignatureFormatError:如果泛型类签名不符合Java™ 虚拟机规范中指定的格式
  • TypeNotPresentException:如果泛型超类引用了不存在的类型声明
  • MalformedParameterizedTypeException:如果泛型超类引用了因任何原因无法实例化的参数化类型

下面的程序演示了 getGenericSuperclass() 方法。
示例 1:

Java
// Java program to demonstrate
// getGenericSuperclass() method
 
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 super class of myClass
        // using getGenericSuperclass() method
        System.out.println(
            "Type of the superclass of myClass: "
            + myClass.getGenericSuperclass());
    }
}


Java
// Java program to demonstrate
// getGenericSuperclass() method
 
public class Test {
 
    class Arr {
    }
 
    public static void main(String[] args)
        throws ClassNotFoundException
    {
        // returns the Class object for Arr
        Class arrClass = Arr.class;
 
        // Get the super class of arrClass
        // using getGenericSuperclass() method
        System.out.println(
            "Type of the superclass of arrClass: "
            + arrClass.getGenericSuperclass());
    }
}


输出:
Class represented by myClass: class Test
Type of the superclass of myClass: class java.lang.Object

示例 2:

Java

// Java program to demonstrate
// getGenericSuperclass() method
 
public class Test {
 
    class Arr {
    }
 
    public static void main(String[] args)
        throws ClassNotFoundException
    {
        // returns the Class object for Arr
        Class arrClass = Arr.class;
 
        // Get the super class of arrClass
        // using getGenericSuperclass() method
        System.out.println(
            "Type of the superclass of arrClass: "
            + arrClass.getGenericSuperclass());
    }
}
输出:
Type of the superclass of arrClass: class java.lang.Object

参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#getGenericSuperclass–