Get Declared Method by name and parameter type in Java

Description

The following code shows how to get Declared Method by name and parameter type.

Example


//from w  ww .j a  v a 2  s.  co  m
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
  private void drinkMe(int liters) {
    if (liters < 0)
      throw new IllegalArgumentException(
          "I can't drink a negative amount of liquid");
  }

  public static void main(String... args) {
    try {
      Main mtr = new Main();
      Class<?> c = mtr.getClass();
      Method m = c.getDeclaredMethod("drinkMe", int.class);
      m.invoke(mtr, -1);

      // production code should handle these exceptions more gracefully
    } catch (InvocationTargetException x) {
      Throwable cause = x.getCause();
      System.err.format("drinkMe() failed: %s%n", cause.getMessage());
    } catch (Exception x) {
      x.printStackTrace();
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy