try { Method method = obj.getClass().getMethod("methodName", parameterTypes); method.invoke(obj, args); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { if (e.getCause() != null) { // Exception was thrown by the invoked method throw (Exception) e.getCause(); } // Exception was not thrown by the invoked method throw new Exception("Failed to invoke method", e); }
try { Constructor constructor = clazz.getConstructor(parameterTypes); constructor.newInstance(args); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { if (e.getCause() != null) { // Exception was thrown by the constructor throw (Exception) e.getCause(); } // Exception was not thrown by the constructor throw new Exception("Failed to create instance", e); }Package: The java.lang.reflect.InvocationTargetException class is part of the Java Standard Library and is located in the java.lang.reflect package.