集册 Java实例教程 使用反射按参数类型调用方法

使用反射按参数类型调用方法

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

459
使用反射按参数类型调用方法
/** from 时代Java公众号 - N o w J a  v a . c o m**/

import java.lang.reflect.Method;


public class MethodTroubleToo {

    public void ping() {

        System.out.format("PONG!%n");

    }


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

        try {

            MethodTroubleToo mtt = new MethodTroubleToo();

            Method m = MethodTroubleToo.class.getMethod("ping");


            switch (Integer.parseInt(args[0])) {

            case 0:

                m.invoke(mtt); // works

                break;

            case 1:

                m.invoke(mtt, null); // works (expect compiler warning)

                break;

            case 2:

                Object arg2 = null;

                m.invoke(mtt, arg2); // IllegalArgumentException
                /*来自 
                 n o w j a v a . c o m - 时代Java*/

                break;

            case 3:

                m.invoke(mtt, new Object[0]); // works

                break;

            case 4:

                Object arg4 = new Object[0];

                m.invoke(mtt, arg4); // IllegalArgumentException

                break;

            default:

                System.out.format("Test not found%n");

            }


            // production code should handle these exceptions more gracefully

        } catch (Exception x) {

            x.printStackTrace();

        }

    }

}


展开阅读全文