Executing a method using reflection

The following example shows you how to. First get a Method instance using the getMethod method executed on any Class object of the class containing that method. Make sure you specify the correct method name and parameter list to uniquely identify the method. Then call invoke on that method instance and specify the object instance on which you want to execute that method and specify the parameters (wrap primitive types in their equivalent object types).

If you want to execute a static method, you don’t need to specify an object instance, it is ignored anyway (use null).
Main.java:

import java.lang.reflect.*;
  
public class Main {
   public static void main(String args[]) {
      MyClass myClass = new MyClass();
      MyClass.MyInnerClass myInnerClass = myClass.new MyInnerClass();
 
      try {
         Method m1 = MyClass.class.getMethod("myMethod", new Class[] { int.class });
         Object ret1 = m1.invoke(myClass, new Object[] { new Integer(1) });
         System.out.println("Returned: " + ret1);
 
         Method m2 = MyClass.class.getMethod("myStaticMethod", new Class[] { });
         Object ret2 = m2.invoke(null, new Object[] { });
 
         Method m3 = MyClass.MyInnerClass.class.getMethod("myInnerMethod", new Class[] { });
        
         Object ret3 = m3.invoke(myInnerClass, new Object[] { });
      }
      catch(NoSuchMethodException e) {
         e.printStackTrace();
      }
      catch(IllegalAccessException e) {
         e.printStackTrace();
      }
      catch(InvocationTargetException e) {
         e.printStackTrace();
      }
   }
}
 
class MyClass
{
   public int myMethod(int n) {
      System.out.println("Dynamically invoked myMethod passing: " + n);
      return n + 10;
   }
 
   public static void myStaticMethod() {
      System.out.println("Dynamically invoked myStaticMethod");
   }
 
   class MyInnerClass {
      public void myInnerMethod() {
         System.out.println("Dynamically invoked myInnerMethod");
      }
   }
}

outputs:

Dynamically invoked myMethod passing: 1
Returned: 11
Dynamically invoked myStaticMethod
Dynamically invoked myInnerMethod