UniversalActionListener.java

Power Java
Limitations of reflective method lookup
by Paul Holser
Listing 1. UniversalActionListener.java.


package reflection;

import javax.swing.*;
import java.awt.event.*;
import java.lang.reflect.*;

public class UniversalActionListener implements ActionListener {
  private Object target;
  private Object arg;
  private Method m;

  public UniversalActionListener(Object target, String methodName, Object arg) throws NoSuchMethodException {
    this.target = target;
    this.arg = arg;

    Class clazz = null;
    Class[] parameterTypes = null;

    clazz = target.getClass();

    parameterTypes =
      (arg == null) ? new Class[0] : new Class[] {arg.getClass()};

    try {
      this.m = clazz.getMethod(methodName, parameterTypes);
    } catch (NoSuchMethodException e) {
      // Sun JDK 1.3 for Windows doesn't give a message in its
      // exception, so let's make our own.

      throw new NoSuchMethodException(
        "Cannot find a method named " + methodName + " in "
          + target.getClass() + " with appropriate argument types");
    }
  }

  public void actionPerformed(ActionEvent event) {
    Object[] arguments =
      (arg == null) ? new Object[0] : new Object[] {arg};

    try {
      m.invoke(target, arguments);
    } catch (IllegalAccessException e) {
      System.err.println("UniversalActionListener: " + e);
    } catch (InvocationTargetException e) {
      System.err.println("UniversalActionListener: " + e);
    }
  }
}

About the Author

Paul Holser is a senior consultant at Valtech, an international consulting group specializing in e-business technologies. He can be contacted at [email protected].