477. Java 反射 - 获取方法的返回类型
在反射中,方法的返回类型和字段的类型处理方式类似。
Reflection 提供了两种方式:
-
Method.getReturnType()→ 返回一个Class<?>,给出方法的原始类型(擦除后类型)。 -
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()