/** * Gets the given arguments corrected to match the given methodSignature. Correction is necessary for array arguments not to be * mistaken by varargs. * * @param parameterTypes the method signatue the given arguments should match * @param arguments the arguments that should be corrected * @return the corrected arguments */ private static Object[] getCorrectedArguments(Class<?>[] parameterTypes, Object[] arguments) { if (arguments == null) return arguments; if (parameterTypes.length > arguments.length) return arguments; if (parameterTypes.length < arguments.length) return getCorrectedArguments(parameterTypes, new Object[] {arguments}); Object[] correctedArguments = new Object[arguments.length]; int currentArgument = 0; for (Class<?> parameterType : parameterTypes) { correctedArguments[currentArgument] = getCorrectedArgument(parameterType, arguments[currentArgument]); currentArgument++; } return correctedArguments; }
/** * Calls a method on the given object instance with the given arguments. Arguments can be object types or representations for * primitives. * * @param instanceOrClass the instance or class to invoke the method on * @param methodSignature the name of the method and the parameters <br> * (e.g. "myMethod(java.lang.String, com.company.project.MyObject)") * @param arguments an array of objects to pass as arguments * @return the return value of this method or null if void * @throws IllegalAccessException if the method is inaccessible * @throws InvocationTargetException if the underlying method throws an exception. * @throws NoSuchMethodException if no method with the given <code>methodSignature</code> could be found * @throws IllegalArgumentException if an argument couldn't be converted to match the expected type */ public static Object invokeMethod(final Object instanceOrClass, final String methodSignature, final Object[] arguments) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { if ((methodSignature.indexOf('(') == -1) || (methodSignature.indexOf('(') >= methodSignature.indexOf(')'))) throw new NoSuchMethodException(methodSignature); Class<?>[] parameterTypes = getParameterTypes(methodSignature); return getMethod(instanceOrClass, getMethodName(methodSignature), parameterTypes).invoke(instanceOrClass, getCorrectedArguments(parameterTypes, arguments)); }