/** * Instantiates an object of the given class with the given arguments. If you want to instantiate a member class, you must provide * the object it is a member of as first argument. * * @param fromClass the class to instantiate an object from * @param args the arguments to pass to the constructor * @return an object of the given type * @throws IllegalArgumentException if the number of actual and formal parameters differ; if an unwrapping conversion for primitive * arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal * parameter type by a method invocation conversion. * @throws IllegalAccessException if this Constructor object enforces Java language access control and the underlying constructor is * inaccessible. * @throws InvocationTargetException if the underlying constructor throws an exception. * @throws NoSuchMethodException if the constructor could not be found * @throws InstantiationException if the class that declares the underlying constructor represents an abstract class. * * @see PrivilegedAccessor#instantiate(Class,Class[],Object[]) */ public static <T> T instantiate(final Class<? extends T> fromClass, final Object[] args) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { return instantiate(fromClass, getParameterTypes(args), args); }
/** * 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)); }