477. Java 反射 - 获取方法的返回类型

477. Java 反射 - 获取方法的返回类型

在反射中,方法的返回类型字段的类型处理方式类似。
Reflection 提供了两种方式:

  1. Method.getReturnType() → 返回一个 Class<?>,给出方法的原始类型(擦除后类型)
  2. Method.getGenericReturnType() → 返回一个 Type,保留泛型信息,能看到方法声明时的泛型参数。

1. 示例:List.get(int)

List.get(int) 方法会返回该 List 中对应索引的元素。
由于 List 是一个泛型接口,返回类型实际上取决于你声明的类型参数。

Class<?> listClass = List.class;
Method getWithIndex = listClass.getMethod("get", int.class);

// 原始返回类型
Class<?> returnType = getWithIndex.getReturnType();
System.out.println("Return type = " + returnType);

// 泛型返回类型
Type genericReturnType = getWithIndex.getGenericReturnType();
System.out.println("Generic return type = " + genericReturnType);

输出结果:

Return type = class java.lang.Object
Generic return type = E

📌 说明:

  • getReturnType() → 看到的是 擦除类型,即 Object
  • getGenericReturnType() → 保留了泛型声明,显示为 E

2. 示例:List.of()

List.of(Object...) 是 Java 9 引入的静态工厂方法,用于创建不可变 List。

Class<?> listClass = List.class;
Method listOf = listClass.getMethod("of", Object.class);

// 原始返回类型
Class<?> returnType = listOf.getReturnType();
System.out.println("Return type = " + returnType);

// 泛型返回类型
Type genericReturnType = listOf.getGenericReturnType();
System.out.println("Generic return type = " + genericReturnType);

输出结果:

Return type = interface java.util.List
Generic return type = java.util.List<E>

📌 说明:

  • getReturnType() 只知道返回的是一个 List 接口
  • getGenericReturnType() 更准确,告诉我们是 List<E>,并保留了泛型

3. 总结

  • getReturnType() → 原始类型(不含泛型信息),适合运行时类型检查
  • getGenericReturnType() → 含泛型信息,更接近源码声明,但仍然受 类型擦除 限制

换句话说:

  • 如果你只关心“这个方法返回的是不是个 List?” → 用 getReturnType()
  • 如果你需要知道“这个方法声明时是 List<E>?” → 用 getGenericReturnType()
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容