java.lang.reflect.Method.getGenericReturnType()方法範例

2019-10-16 22:48:06

java.lang.reflect.Method.getGenericReturnType()方法返回一個Type物件,該物件表示此Method物件表示的方法的正式返回型別。

宣告

以下是java.lang.reflect.Method.getGenericReturnType()方法的宣告。

public Type getGenericReturnType()

引數

  • NA

返回值

  • 一個Type物件,表示底層方法的正式返回型別。

異常

  • GenericSignatureFormatError - 如果通用方法簽名不符合Java虛擬機器規範中指定的格式。

  • TypeNotPresentException - 如果底層方法的throws子句參照不存在的型別宣告。

  • MalformedParameterizedTypeException - 如果底層方法的throws子句參照了由於任何原因無法範例化的引數化型別。

以下範例顯示java.lang.reflect.Method.getGenericReturnType()方法的用法。

import java.lang.reflect.Method;
import java.lang.reflect.Type;

public class MethodDemo {

   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      Type returnType = methods[0].getGenericReturnType();
      System.out.println(returnType);
   }
}

class SampleClass {
   private String sampleField;

   public String getSampleField() {
      return sampleField;
   }

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

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

class java.lang.String