Here you can find the source of invokeMethod(Object theObject, String methodName, Object... parametersObject)
Parameter | Description |
---|---|
theObject | the object on which to invoke the method |
methodName | the methods name |
parameters | the parameters |
public static Object invokeMethod(Object theObject, String methodName, Object... parametersObject)
//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); } } }