In the Java reflection API, a method of a class or interface is represented by the java.lang.reflect.Method class. An object of this class can reflect either a class method or an instance method. The Method class allows not only retrieving information about a given method, such as its name, its parameter list, its return type, the exceptions it can throw, etc., but also invoking the method on a given object.

A Method object representing a method in a given class is retrieved from the corresponding java.lang.Class object, by calling either getMethods(), which returns an array of objects representing the public methods of the class, or getMethod(String name, Class<?>... parameterTypes), which takes as arguments the method name and the types of its parameters (in the order in which they are defined) and returns the object representing the requested method. Once this object has been retrieved, the method it represents can be invoked by calling invoke(Object obj, Object... args), which takes as arguments the object on which to invoke the method and the list of arguments (if any) to be passed to the method invocation, and returns the return value from the invocation.

The simple example below shoes how to call a method using reflection.


import java.lang.reflect.*;

public class MethodCallExample {
  public static void main(String[] args) {
    String firstName = new String("John");
    String lastName = new String("Smith");
    Class[] parameterTypes = new Class[] {String.class};
    Object[] arguments = new Object[] {lastName};
    try {
      Method concatMethod = 
        String.class.getMethod("concat", parameterTypes);
      String result =
        (String) concatMethod.invoke(firstName, arguments);
      System.out.println("The concatenated string is: " + result);
    } catch (Exception e) {

The above code retrieves the Method object representing the concat(String str) method of the java.lang.String class, and then invokes it on the firstName object, passing lastName as argument; the result of the method invocation is printed on the standard output. Running this program gives the following output: 


 The concatenated string is: JohnSmith