public class TestClass { public static void main(String[] args) { try { Method method = String.class.getMethod("nonExistingMethod"); method.invoke("test"); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { System.out.println("Exception caught: " + e); } } }
public class TestClass { public static void main(String[] args) { try { Constructor constructor = String.class.getConstructor(int.class); constructor.newInstance("test"); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { System.out.println("Exception caught: " + e); } } }In this example, we are trying to instantiate a String object using a constructor that accepts an integer parameter. However, we are passing a String parameter instead, which will result in an InvocationTargetException. Both examples use the java.lang.reflect package to reflectively invoke methods and constructors.