/** * Return the named method with a method signature matching classTypes from the given class. * * @param type the class to get the method from * @param methodName the name of the method to get * @param parameterTypes the parameter-types of the method to get * @return the method * @throws NoSuchMethodException if the method could not be found */ private static Method getMethod(final Class<?> type, final String methodName, final Class<?>[] parameterTypes) throws NoSuchMethodException { try { return type.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { if (type.getSuperclass() == null) throw e; return getMethod(type.getSuperclass(), methodName, parameterTypes); } }
/** * 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)); }
/** * Gets the method with the given name and parameters from the given instance or class. If instanceOrClass is a class, then we get a * static method. * * @param instanceOrClass the instance or class to get the method of * @param methodName the name of the method * @param parameterTypes the parameter-types of the method to get * @return the method * @throws NoSuchMethodException if the method could not be found */ private static Method getMethod(final Object instanceOrClass, final String methodName, final Class<?>[] parameterTypes) throws NoSuchMethodException { Class<?> type; type = getClass(instanceOrClass); Method accessMethod = getMethod(type, methodName, parameterTypes); accessMethod.setAccessible(true); return accessMethod; }