Here you can find the source of invokeMethod(Method method, Object target)
Parameter | Description |
---|---|
method | the method to invoke |
target | the target object to invoke the method on |
public static Object invokeMethod(Method method, Object target)
//package com.java2s; //License from project: Apache License import java.lang.reflect.*; public class Main { /**//w w w . j a v a 2 s . c om * Invoke the specified {@link Method} against the supplied target object with no arguments. * The target object can be {@code null} when invoking a static {@link Method}. * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException}. * * @param method the method to invoke * @param target the target object to invoke the method on * @return the invocation result, if any * @see #invokeMethod(java.lang.reflect.Method, Object, Object[]) */ public static Object invokeMethod(Method method, Object target) { return invokeMethod(method, target, new Object[0]); } /** * Invoke the specified {@link Method} against the supplied target object with the * supplied arguments. The target object can be {@code null} when invoking a * static {@link Method}. * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException}. * * @param method the method to invoke * @param target the target object to invoke the method on * @param args the invocation arguments (may be {@code null}) * @return the invocation result, if any */ public static Object invokeMethod(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (Exception ex) { handleReflectionException(ex); } throw new IllegalStateException("Should never get here"); } /** * Handle the given reflection exception. Should only be called if no * checked exception is expected to be thrown by the target method. * <p>Throws the underlying RuntimeException or Error in case of an * InvocationTargetException with such a root cause. Throws an * IllegalStateException with an appropriate message else. * * @param ex the reflection exception to handle */ public static void handleReflectionException(Exception ex) { if (ex instanceof NoSuchMethodException) { throw new IllegalStateException("Method not found: " + ex.getMessage()); } if (ex instanceof IllegalAccessException) { throw new IllegalStateException("Could not access method: " + ex.getMessage()); } if (ex instanceof InvocationTargetException) { throw new IllegalStateException("Could not access method: " + ex.getMessage()); } if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new UndeclaredThrowableException(ex); } }