集册 Java实例教程 使用反射按名称和参数类型获取方法

使用反射按名称和参数类型获取方法

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

471
使用反射按名称和参数类型获取方法
/*时代Java*/

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;


public class MethodTroubleReturns {

    private void drinkMe(int liters) {

        if (liters < 0)

            throw new IllegalArgumentException(

                    "I can't drink a negative amount of liquid");

    }


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

        try {

            MethodTroubleReturns mtr = new MethodTroubleReturns();

            Class<?> c = mtr.getClass();

            Method m = c.getDeclaredMethod("drinkMe", int.class);

            m.invoke(mtr, -1);
/*N o  w  J a v a . c o m - 时  代  Java*/

            // production code should handle these exceptions more gracefully

        } catch (InvocationTargetException x) {

            Throwable cause = x.getCause();

            System.err.format("drinkMe() failed: %s%n", cause.getMessage());

        } catch (Exception x) {

            x.printStackTrace();

        }

    }

}


展开阅读全文