java.lang.reflect.Constructor.getExceptionTypes()方法範例

2019-10-16 22:49:02

java.lang.reflect.Constructor.getExceptionTypes()方法返回一個Class物件陣列,該物件表示由此構造方物件表示的底層建構函式宣告的異常型別。 如果建構函式在其throws子句中宣告沒有異常,則返回一個長度為0的陣列。

宣告

以下是java.lang.reflect.Constructor.getExceptionTypes()方法的宣告。

public Class<?>[] getExceptionTypes()

返回值

宣告為由此物件表示的建構函式丟擲的異常型別。

例子

以下範例顯示了java.lang.reflect.Constructor.getExceptionTypes()方法的用法。


import java.lang.reflect.Constructor;

public class GetExceptionTypes {

   public static void main(String[] args) {
      Constructor[] constructors = SampleClass.class.getConstructors();
      Class[] exceptions = constructors[0].getExceptionTypes();
      for (int i = 0; i < exceptions.length; i++) {
         System.out.println(exceptions[i]);
      }
   }
}

class SampleClass {
   private String sampleField;

   public SampleClass() throws ArrayIndexOutOfBoundsException {
   }

   public SampleClass(String sampleField){
      this.sampleField = sampleField;
   }

   public String getSampleField() {
      return sampleField;
   }

   public void setSampleField(String sampleField) {
      this.sampleField = sampleField; 
   } 
}

讓我們編譯並執行上面的程式,這將產生以下結果 -

class java.lang.ArrayIndexOutOfBoundsException