集册 Java实例教程 使用反射获取方法返回类型

使用反射获取方法返回类型

欢马劈雪     最近更新时间:2020-01-02 10:19:05

420
使用反射获取方法返回类型

import java.lang.reflect.Method;

import java.lang.reflect.Type;// from 时 代 J a v a 公 众 号

import static java.lang.System.out;


public class MethodSpy {

    private static final String fmt = "%24s: %s%n";


    // for the morbidly curious

    <E extends RuntimeException> void genericThrow() throws E {

    }


    public static void main(String... args) {

        try {

            Class<?> c = Class.forName(args[0]);

            Method[] allMethods = c.getDeclaredMethods();

            for (Method m : allMethods) {/**from N o w J a v a . c o m - 时代Java**/

                if (!m.getName().equals(args[1])) {

                    continue;

                }

                out.format("%s%n", m.toGenericString());


                out.format(fmt, "ReturnType", m.getReturnType());

                out.format(fmt, "GenericReturnType",

                        m.getGenericReturnType());


                Class<?>[] pType = m.getParameterTypes();

                Type[] gpType = m.getGenericParameterTypes();

                for (int i = 0; i < pType.length; i++) {

                    out.format(fmt, "ParameterType", pType[i]);

                    out.format(fmt, "GenericParameterType", gpType[i]);

                }


                Class<?>[] xType = m.getExceptionTypes();

                Type[] gxType = m.getGenericExceptionTypes();

                for (int i = 0; i < xType.length; i++) {

                    out.format(fmt, "ExceptionType", xType[i]);

                    out.format(fmt, "GenericExceptionType", gxType[i]);

                }

            }


            // production code should handle these exceptions more gracefully

        } catch (ClassNotFoundException x) {

            x.printStackTrace();

        }

    }

}


展开阅读全文