Description
Invokes specified method using reflection and returns result.
License
Open Source License
Parameter
Parameter | Description |
---|
clazz | Class, which method will be get by name. |
obj | Object, which method will be invoked. |
methodName | Name of method, that will be invoked. |
parametersTypes | Array of parameter types, used for getting method. |
parameters | Array with arguments, that will be passed to method. |
Exception
Parameter | Description |
---|
Exception | To JUnit. |
Return
Result of method invoking.
Declaration
public static Object invokeMethod(Class clazz, Object obj, String methodName, Class[] parametersTypes,
Object[] parameters) throws Exception
Method Source Code
//package com.java2s;
import java.lang.reflect.Method;
public class Main {
/**/*from w ww . j a v a 2s. c o m*/
* Invokes specified method using reflection and returns result. Here, necessary method will be get from
* specified class: clazz.getDeclaredMethod().
*
* @param clazz Class, which method will be get by name.
* @param obj Object, which method will be invoked.
* @param methodName Name of method, that will be invoked.
* @param parametersTypes Array of parameter types, used for getting method.
* @param parameters Array with arguments, that will be passed to method.
* @return Result of method invoking.
* @throws Exception To JUnit.
*/
public static Object invokeMethod(Class clazz, Object obj, String methodName, Class[] parametersTypes,
Object[] parameters) throws Exception {
Method method = clazz.getDeclaredMethod(methodName, parametersTypes);
method.setAccessible(true);
return method.invoke(obj, parameters);
}
/**
* Invokes specified method using reflection and returns result. Here, necessary method will be get using
* object's class: obj.getClass().getDeclaredMethod().
*
* @param obj Object, which method will be invoked.
* @param methodName Name of method, that will be invoked.
* @param parametersTypes Array of parameter types, used for getting method.
* @param parameters Array with arguments, that will be passed to method.
* @return Result of method invoking.
* @throws Exception To JUnit.
*/
public static Object invokeMethod(Object obj, String methodName, Class[] parametersTypes, Object[] parameters)
throws Exception {
return invokeMethod(obj.getClass(), obj, methodName, parametersTypes, parameters);
}
}
Related
- invoke(Method method, T instance, Object... params)
- invoke(MethodHandle methodHandle, Object... params)
- invokeJdbcMethod(Method method, Object target)
- invokeJdbcMethod(Method method, Object target)
- invokeMethod(Class clazz, Object classObject, String methodName, Class[] paramTypes, Object... args)
- invokeMethod(Class clazz, String methodName, Object[] args)
- invokeMethod(Class targetClass, Object obj, String methodName, Object arg)
- invokeMethod(Class extends E> clazz, E instance, String[] names, Object... args)
- invokeMethod(Class> clazz, Object object, String methodName, Class>[] parameterTypes, Object[] parameters)