Java Constructor getGenericExceptionTypes()方法及示例

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

Java Constructor getGenericExceptionTypes()方法及示例

java.lang.reflect.Constructor类getGenericExceptionTypes() 方法用于以数组形式返回该构造器对象上存在的异常类型。返回的对象数组代表这个构造函数对象所声明的异常。如果该构造函数在其 throws 子句中没有声明任何异常,那么该方法返回一个长度为 0 的数组。

语法

public Type[] getGenericExceptionTypes()

参数: 此方法不接受任何东西。

返回 :该方法返回一个 Types数组 ,代表底层可执行文件抛出的异常类型。

异常: 该方法会抛出以下异常。

GenericSignatureFormatError:如果通用方法签名不符合The Java™ Virtual Machine Specification中规定的格式。TypeNotPresentException:如果底层可执行文件的throws子句指向一个不存在的类型声明。MalformedParameterizedTypeException:如果底层可执行文件的throws子句指的是一个由于任何原因不能实例化的参数化类型。

下面的程序说明了getGenericExceptionTypes()方法:

程序1 :

// Java program to illustrate// getGenericExceptionTypes() method  import java.io.IOException;import java.lang.reflect.*;  public class GFG {      public static void main(String[] args)    {        // create a class object        Class classObj = shape.class;          // get Constructor object        // array from class object        Constructor[] cons            = classObj.getConstructors();          // get array of GenericExceptionTypes        Type[] exceptions            = cons[0].getGenericExceptionTypes();          // print length of GenericExceptionTypes array        System.out.println("GenericExceptions : ");          for (int i = 0; i < exceptions.length; i++)            System.out.println(exceptions[i]);    }      // demo class    public class shape {          public shape() throws IOException,                              ArithmeticException,                              ClassCastException        {        }    }}

输出。

GenericExceptions : class java.io.IOExceptionclass java.lang.ArithmeticExceptionclass java.lang.ClassCastException

程序2

// Java program to illustrate// getGenericExceptionTypes() method  import java.lang.reflect.Constructor;import java.lang.reflect.Type;  public class GFG {      public static void main(String[] args)    {        // create a class object        Class classObj = String.class;          // get Constructor object        // array from class object        Constructor[] cons            = classObj.getConstructors();          // get array of GenericExceptionTypes        Type[] exceptions            = cons[0].getGenericExceptionTypes();          // print length of GenericExceptionTypes array        System.out.println(            "No of Generic Exception thrown : "            + exceptions.length);    }}

输出。

No of Generic Exception thrown : 0

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

相关推荐