获取方法的返回值类型
| 方法 | 描述 | 
|---|---|
Type getGenericReturnType() | 
返回表示返回值类型的Type对象 | 
Class<?> getReturnType() | 
返回表示返回值类型的Class对象 | 
这两个方法的区别主要是在返回值类型上:
-Type是一个接口
-Class是一个Type接口的子类.
-Type接口只有一个方法
-Class类方法比较多
Type接口方法
| 方法 | 描述 | 
|---|---|
default String getTypeName() | 
Returns a string describing this type, including information about any type parameters. | 
这个方法会返回返回值类型的全限定名,如:
-java.lang.String
-void
Class类获取类名方法
| 方法 | 描述 | 
|---|---|
String getName() | 
Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String. | 
这个方法也会返回类的全限定名,和上面的一样.
获取方法的返回值类型名称
所以如果想获取一个方法的返回值类型的名称,使用如下两种方式都可以:
method.getReturnType().getName();method.getGenericReturnType().getTypeName();
封装成方法
1  | public static String getMethodReturnTypeName1(Method method) {  | 
程序示例
1  | package returntype;  | 
测试类:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45package returntype;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
public class TestMethodReturnType {
    public static void main(String[] args) throws Exception {
        // 加载类
        Class<?> class1 = Class.forName("returntype.Return");
        //testReturnType1(class1);
        testReturnType2(class1);
    }
    private static void testReturnType2(Class<?> class1) {
        Method[] methods = class1.getDeclaredMethods();
        for (Method method : methods) {
            System.out.print("方法名:" + method.getName());
            System.out.print(" 返回值类型1:" + getMethodReturnTypeName1(method));
            System.out.println(" 返回值类型2:" + getMethodReturnTypeName2(method));
        }
    }
    private static void testReturnType1(Class<?> class1) {
        // 获取所有的方法
        Class returnType1;
        Type returnType2;
        Method[] methods = class1.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            returnType1 = methods[i].getReturnType();
            returnType2 = methods[i].getGenericReturnType();
            System.out.print("方法名称:" + methods[i].getName());
            System.out.print(" 返回值类型1:" + returnType1.getName());
            System.out.println(" 返回值类型2:" + returnType2.getTypeName());
        }
    }
    public static String getMethodReturnTypeName1(Method method) {
        return method.getGenericReturnType().getTypeName();
    }
    public static String getMethodReturnTypeName2(Method method) {
        return method.getReturnType().getName();
    }
}
运行结果:1
2方法名:returnVoidMethod 返回值类型1:void 返回值类型2:void
方法名:returnStringMethod 返回值类型1:java.lang.String 返回值类型2:java.lang.String