Here you can find the source of invokeMethod(Object obj, Class type, String name, Class[] parameterTypes, Object[] parameters)
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 |
Parameter | Description |
---|---|
Exception | if any error happens. |
public static Object invokeMethod(Object obj, Class type, String name, Class[] parameterTypes, Object[] parameters) throws Exception
//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(); } } }