Sun Java Solaris Communities My SDN Account Join SDN
 
Tutorials & Code Camps

Program Challenge

 
New to Java Programming Center

Java Technology Fundamentals
January's Program Challenge
New to Java Programming Center

Java Platform Overview | Getting Started | Step-by-Step Programming
Learning Paths | References & Resources | Courses & Certification | Newsletters


The Java Reflection API offers Class.getMethod() to locate the method of a class and Method.invoke() to invoke that method. Since these methods have been around for some time, they deal with arrays of variable length, instead of argument lists of variable lengths. To facilitate their usage, create a new helper class with a single method that takes a variable argument list:

public class MethodInvoker {
  public static Object invokeMethod(
    Object instance,
    String name,
    Object... args)
}

Implement the method to invoke the original two methods.

Possible Solution:

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

public class MethodInvoker {
  public static Object invokeMethod(
    Object instance,
    String name,
    Object... args) {

      Object returnValue = null;

      try {
        Class theClass = instance.getClass();
        Class parameterTypes[] = new Class[args.length];
        for (int i=0, n=args.length; i<n; i++) {
          parameterTypes[i] = args[i].getClass();
        }
        Method method = theClass.getMethod(name, parameterTypes);
        returnValue = method.invoke(instance, args);
      } catch (NoSuchMethodException e) {
        System.err.println("Invalid method name: " + name);
      } catch (IllegalAccessException e) {
        System.err.println("Invalid method access: " + name);
      } catch (InvocationTargetException e) {
        System.err.println("Invalid method invocation:   + name);
      }
      return returnValue;
  }

  public static void main(String args[]) {
    // Test: "Hello, World".replaceAll("o", "a");
    System.out.println(
      MethodInvoker.invokeMethod(
              "Hello, World",
              "replaceAll",
              "o", "a"));
  }
}