Call all possible exceptions during method invocation with reflection in Java

Description

The following code shows how to call all possible exceptions during method invocation with reflection.

Example


// w  ww  .j ava 2s.com
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
  public static void main(String[] args) {
    try {
      Class c = Class.forName("java.lang.String");
      Method m = c.getMethod("toString");
      Object ret = m.invoke(null);
      System.out.println("Invoked static method: " + args[1] + " of class: " + args[0]
          + " with no args\nResults: " + ret);
    } catch (ClassNotFoundException e) {
      System.out.println(e);
    } catch (NoSuchMethodException e2) {
      System.out.println(e2);
    } catch (IllegalAccessException e3) {
      System.out.println(e3);
    } catch (InvocationTargetException e) {
      System.out.println(e);
      System.out.println("Method threw an: " + e.getTargetException());
    }
  }
}




















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy