JTechDev

Method Reflection Java Example

In this example I will show you how to use basic Java Reflection tricks to call a Java method from a String. This is a surprisingly simple task. You can find out more about the Java Reflection API on the Java Tutorial Trail.

First the code of the method:

/**
* Write out the Strings.
* 
* @param args The Strings to print out
*/
public static void printMessage(Object... args) {
      for (int i = 0; i < args.length; i++) {
           String s = (String)args[i];
           System.out.println(s);
      }
}

Then the code to call the method through a String:

try {
      Method s = MethodController.class.getMethod("printMessage", Object[].class);
      Object[] ex = new Object[1];
      ex[0] = "Hello World";
      s.invoke(this, (Object) ex);
} catch (NoSuchMethodException ex) {
      // Throw error
} catch (SecurityException ex) {
      // Throw error
} catch (IllegalAccessException ex) {
      // Throw error
} catch (IllegalArgumentException ex) {
      // Throw error
} catch (InvocationTargetException ex) {
      // Throw error
}

This will call the method “printMessage” and give it the Object[] with one object “Hello World”. The printMessage() method will then go through the Object[] and print them out.