Java Reflection Method Invoke invokeMethod(Object theObject, String methodName, Object... parametersObject)

Here you can find the source of invokeMethod(Object theObject, String methodName, Object... parametersObject)

Description

reflectively invokes the method on the object and catches all exceptions and wraps them in RuntimeExceptions

License

Apache License

Parameter

Parameter Description
theObject the object on which to invoke the method
methodName the methods name
parameters the parameters

Return

the return value

Declaration

public static Object invokeMethod(Object theObject, String methodName, Object... parametersObject) 

Method Source Code

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

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

public class Main {
    /**// w  w w .  j a  v  a  2 s. c o m
     * reflectively invokes the method on the object and catches all exceptions and wraps them in RuntimeExceptions
     * 
     * @param theObject the object on which to invoke the method
     * @param methodName the methods name
     * @param parameters the parameters
     * @return the return value
     */
    public static Object invokeMethod(Object theObject, String methodName, Object... parametersObject) {

        try {
            Class<?>[] parameters = new Class<?>[parametersObject.length];
            for (int i = 0; i < parameters.length; i++) {
                parameters[i] = parametersObject[i].getClass();
            }
            Method method = theObject.getClass().getMethod(methodName, parameters);
            Object returnValue = method.invoke(theObject, parametersObject);
            return returnValue;
        } catch (NoSuchMethodException | SecurityException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);

        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }

    }
}

Related

  1. invokeMethod(Object target, String methodName, Object[] arguments)
  2. invokeMethod(Object target, String name, Class... parameterTypes)
  3. invokeMethod(Object target, String name, Object[] args, Class[] argTypes)
  4. invokeMethod(Object target, String signature, Object... args)
  5. invokeMethod(Object target, String thisMethod, Object value)
  6. invokeMethod(String className, String method, Class[] paramTypes, Object obj, Object[] args)
  7. invokeMethod(String methodName, Object gameCommand)
  8. invokeMethod(String name, Object target)
  9. invokeMethod2(Class cls, Object obj, String methodName, Object[] args)