📜  方法类 | Java中的 getGenericExceptionTypes() 方法

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

方法类 | Java中的 getGenericExceptionTypes() 方法

Java.lang.reflectMethod 类的getGenericExceptionTypes()方法返回一个Type 对象数组,表示方法对象抛出的异常以处理异常。使用 throwed 子句的方法处理的所有异常都作为使用此方法的 Type 对象数组返回。如果应用此方法的方法在其 throws 子句中未声明异常,则此方法返回长度为 0 的数组。

例子:

Code:
public class demo{
    public void setValue(String value)
    throws ClassNotFoundException, ArrayIndexOutOfBoundsException, 
            ArithmeticException {}
}
Explanation:
In the above method when we going to apply getGenericExceptionTypes() method
it is going to return array of the exception types.
Array = {
          java.lang.ClassNotFoundException,
          java.lang.ArrayIndexOutOfBoundsException,
          java.lang.ArithmeticException,
        }

句法:

public Type[] getGenericExceptionTypes()

返回值:返回this Method对象抛出的异常类型数组

异常:此方法抛出以下异常:

  • GenericSignatureFormatError – 如果通用方法签名与 JVM 规范中指定的格式不同。
  • TypeNotPresentException – 如果 throws 子句指定的异常类型引用不存在的类型声明。
  • MalformedParameterizedTypeException – 如果底层可执行文件的 throws 子句引用了因任何原因无法实例化的参数化类型。

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

程序 1:在 getGenericExceptionTypes() 的帮助下打印方法抛出的所有异常类型

/*
* Program Demonstrate how to apply 
* getGenericExceptionTypes() method
*/
import java.lang.reflect.Method;
import java.lang.reflect.Type;
  
public class GFG {
  
    // Main method
    public static void main(String[] args)
    {
        try {
            // create class object
            Class classobj = demoClass.class;
  
            // create parameter type of string
            Class[] parameterTypes = { String.class };
  
            // get list of method objects
            Method[] methods = classobj.getMethods();
  
            // loop through all methods
            for (Method m : methods) {
  
                if (m.getName().equals("setValue")
                    || m.getName().equals("getValue")) {
  
                    // apply getGenericExceptionTypes() method
                    Type[] genericExceptions = m.getGenericExceptionTypes();
  
                    // print exception Types thrown by method Object
                    System.out.println("Generic Exception Thrown by Method: "
                                       + m.getName());
  
                    System.out.println("Generic Exception Type Array length: "
                                       + genericExceptions.length);
  
                    // If method has Exception then print
                    if (genericExceptions.length > 0) {
  
                        System.out.println("Exception class object details:");
  
                        for (Type type : genericExceptions) {
  
                            System.out.println(type.getTypeName());
                        }
                    }
                    System.out.println();
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
// a simple class
class demoClass {
  
    String value;
  
    // throw some exception by method
    public void setValue(String value)
        throws ClassNotFoundException,
               ArrayIndexOutOfBoundsException,
               ArithmeticException
    {
        this.value = value;
    }
  
    // method throwing no exception
    public String getValue()
    {
        return this.value;
    }
}
输出:
Generic Exception Thrown by Method: getValue
Generic Exception Type Array length: 0

Generic Exception Thrown by Method: setValue
Generic Exception Type Array length: 3
Exception class object details:
java.lang.ClassNotFoundException
java.lang.ArrayIndexOutOfBoundsException
java.lang.ArithmeticException

程序 2:检查特定异常

/*
* Program Demonstrate how to 
* apply getGenericExceptionTypes() method
*/
  
import java.lang.reflect.Method;
import java.lang.reflect.Type;
  
public class GFG {
  
    // a simple class
    class GFGSampleClass {
  
        String value;
  
        // throw some exception by method
        public void setValue(String value)
            throws ClassNotFoundException,
                   ArrayIndexOutOfBoundsException,
                   ArithmeticException
        {
            this.value = value;
        }
    }
  
    // Main method
    public static void main(String[] args)
    {
        try {
            // create class object
            Class classobj = GFGSampleClass.class;
  
            // get list of method objects
            Method[] methods = classobj.getMethods();
  
            // get Method Object for setValue
            Method method = null;
            for (Method m : methods) {
                if (m.getName().equals("setValue"))
                    method = m;
            }
  
            // check whether method throw
            // ArithmeticException Exception
            Type airthmeticExClassobj = ArithmeticException.class;
  
            boolean response = isCertainExceptionIsThrown(method,
                                                          airthmeticExClassobj);
            System.out.println("ArithmeticException"
                               + " is thrown by setValue(): " + response);
  
            // check whether method throw
            // IndexOutOfBoundsException Exception
            Type exceptionObj = IndexOutOfBoundsException.class;
  
            response = isCertainExceptionIsThrown(method,
                                                  exceptionObj);
            System.out.println("IndexOutOfBoundsException"
                               + " is thrown by setValue(): " + response);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
  
    /*
    * Return true if the given method throws the 
    * exception passed AS Parameter.
    */
    private static boolean
    isCertainExceptionIsThrown(Method method, Type exceptionName)
    {
        // get all exception list using getGenericExceptionTypes()
        Type exceptions[] = method.getGenericExceptionTypes();
  
        for (int i = 0; i < exceptions.length; i++) {
            // check exception thrown or not
            if (exceptions[i] == exceptionName) {
                return true;
            }
        }
  
        return false;
    }
}
输出:
ArithmeticException is thrown by setValue(): true
IndexOutOfBoundsException is thrown by setValue(): false

参考:
https://docs.oracle.com/javase/8/docs/api/java Java