要获取 Java 中 Method 的返回类型,可以使用 getReturnType() 方法。这个方法返回一个 Class 对象,表示方法的返回类型。

下面是一个示例代码:

import java.lang.reflect.Method;

public class Main {
  public static void main(String[] args) {
    try {
      // 获取 String 类的 length 方法
      Method method = String.class.getMethod("length");
      
      // 获取返回类型
      Class<?> returnType = method.getReturnType();
      
      System.out.println("返回类型: " + returnType.getName());
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    }
  }
}

输出结果为:

返回类型: int

这个示例中,使用 getMethod() 方法获取了 String 类的 length 方法,并使用 getReturnType() 方法获取了方法的返回类型。最后输出了返回类型的名称

java 获取 Method 返回类型

原文地址: https://www.cveoy.top/t/topic/h1DG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录