Type getGenericReturnType()

优质
小牛编辑
117浏览
2023-12-01

描述 (Description)

java.lang.reflect.Method.getGenericReturnType()方法返回一个Type对象,该对象表示此Method对象表示的方法的正式返回类型。

声明 (Declaration)

以下是java.lang.reflect.Method.getGenericReturnType()方法的声明。

public Type getGenericReturnType()

返回值 (Returns)

一个Type对象,表示底层方法的正式返回类型。

异常 (Exceptions)

  • GenericSignatureFormatError - 如果泛型方法签名不符合Java虚拟机规范中指定的格式。

  • TypeNotPresentException - 如果基础方法的任何参数类型引用不存在的类型声明。

  • MalformedParameterizedTypeException - 如果任何基础方法的参数类型引用无法因任何原因而实例化的参数化类型。

例子 (Example)

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

package cn.xnip;
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