Java Reflection Method Invoke invokeMethod(Object target, String methodName, Object... parameters)

Here you can find the source of invokeMethod(Object target, String methodName, Object... parameters)

Description

invoke Method

License

Open Source License

Declaration

public static Object invokeMethod(Object target, String methodName, Object... parameters) 

Method Source Code

//package com.java2s;
/* /*from   ww  w  .ja  v  a  2 s  .  co  m*/
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.lang.reflect.Method;

public class Main {
    public static Object invokeMethod(Object target, String methodName, Object... parameters) {
        try {
            final Method method = extractMethod(target, methodName);
            method.setAccessible(true);
            return method.invoke(target, parameters);
        } catch (Exception e) {
            throw new RuntimeException("Could not invoke method.", e);
        }
    }

    public static Method extractMethod(Object target, String methodName) {
        final Method[] declaredMethods = target.getClass().getDeclaredMethods();
        for (Method method : declaredMethods) {
            if (method.getName().equals(methodName)) {
                return method;
            }
        }

        throw new RuntimeException("Method not found: " + methodName);
    }
}

Related

  1. invokeMethod(Object target, Method method)
  2. invokeMethod(Object target, Method method)
  3. invokeMethod(Object target, Method method, Object... args)
  4. invokeMethod(Object target, Method method, Object[] args)
  5. invokeMethod(Object target, String method)
  6. invokeMethod(Object target, String methodName, Object[] arguments)
  7. invokeMethod(Object target, String name, Class... parameterTypes)
  8. invokeMethod(Object target, String name, Object[] args, Class[] argTypes)
  9. invokeMethod(Object target, String signature, Object... args)