Java Reflection Method Invoke invokeMethod(Object obj, Class type, String name, Class[] parameterTypes, Object[] parameters)

Here you can find the source of invokeMethod(Object obj, Class type, String name, Class[] parameterTypes, Object[] parameters)

Description

Invokes a method using reflection, pass out exception from invoked method.

License

Open Source License

Parameter

Parameter Description
obj the object to invoke on
type the type of obj
name the name of the method
parameterTypes the parameter types of the method
parameters the parameters

Exception

Parameter Description
Exception if any error happens.

Return

the return value, or null if the method is a void-return one

Declaration

public static Object invokeMethod(Object obj, Class type, String name,
        Class[] parameterTypes, Object[] parameters) throws Exception 

Method Source Code

//package com.java2s;

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

public class Main {
    /**//from   www . j  a  v a 2 s .  c  o m
     * Invokes a method using reflection, pass out exception from invoked
     * method.
     * @param obj the object to invoke on
     * @param type the type of obj
     * @param name the name of the method
     * @param parameterTypes the parameter types of the method
     * @param parameters the parameters
     * @return the return value, or null if the method is a void-return one
     * @throws Exception if any error happens.
     */
    public static Object invokeMethod(Object obj, Class type, String name,
            Class[] parameterTypes, Object[] parameters) throws Exception {
        Method method = type.getDeclaredMethod(name, parameterTypes);

        try {
            // check isAccessible
            if (method.isAccessible()) {
                return method.invoke(obj, parameters);
            } else {
                try {
                    method.setAccessible(true);

                    return method.invoke(obj, parameters);
                } finally {
                    // set isAccessible back
                    method.setAccessible(false);
                }
            }
        } catch (InvocationTargetException ite) {
            // pass out exception from invoked method.
            throw (Exception) ite.getCause();
        }
    }
}

Related

  1. invokeMethod(Object handler, String strMethod, Class[] cls, Object... params)
  2. invokeMethod(Object instance, String methodName, Class expectedReturnType)
  3. invokeMethod(Object o, String fieldName)
  4. invokeMethod(Object o, String methodName, Object... args)
  5. invokeMethod(Object o, String methodName, Object[] params)
  6. invokeMethod(Object obj, Method method, Object... args)
  7. invokeMethod(Object obj, String mehtodName, Object... parameter)
  8. invokeMethod(Object obj, String method)
  9. invokeMethod(Object obj, String method, Object... args)