Java Reflection Method Invoke invokeMethod(final Object object, final String methodName, final Class[] parameterTypes, final Object[] parameters)

Here you can find the source of invokeMethod(final Object object, final String methodName, final Class[] parameterTypes, final Object[] parameters)

Description

invoke Method

License

Apache License

Declaration

public static Object invokeMethod(final Object object, final String methodName, final Class<?>[] parameterTypes,
        final Object[] parameters) throws InvocationTargetException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {

    public static Object invokeMethod(final Object object, final String methodName, final Class<?>[] parameterTypes,
            final Object[] parameters) throws InvocationTargetException {
        Method method = getDeclaredMethod(object, methodName, parameterTypes);
        if (method == null)
            throw new IllegalArgumentException(
                    "Could not find method [" + methodName + "] on target [" + object + "]");

        method.setAccessible(true);/*from  w  w w.  j av  a 2 s .c o  m*/

        try {
            return method.invoke(object, parameters);
        } catch (IllegalAccessException e) {

        }

        return null;
    }

    protected static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes) {
        for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
                .getSuperclass()) {
            try {
                return superClass.getDeclaredMethod(methodName, parameterTypes);
            } catch (NoSuchMethodException e) {

            }
        }
        return null;
    }
}

Related

  1. invokeMethod(final Method method, final Object object)
  2. invokeMethod(final Method method, final Object object, final Object[] args)
  3. invokeMethod(final Object instance, final String methodName, final Class[] parTypes, final Object[] parameters)
  4. invokeMethod(final Object obj, final Method method, final Object... args)
  5. invokeMethod(final Object obj, final String methodName, final boolean throwException)
  6. invokeMethod(final Object object, final String methodName, final Class[] paramTypes, final Object[] parameters)
  7. invokeMethod(final Object p, final String methodName)
  8. invokeMethod(java.lang.Object toObj, String tcMethodName, Class toResultClass)
  9. invokeMethod(Method inMethod, Object inObject, Object[] inArgs)