package ie.dcu.swt; import java.io.Serializable; import java.lang.reflect.*; import java.util.logging.*; import org.eclipse.swt.widgets.*; /** * Dispatches method calls that take an Event parameter by reflection. * * @author Kevin McGuinness */ public class EventDispatcher implements Serializable, Listener { /** * Serialization UID. */ private static final long serialVersionUID = 7238671421599697388L; /** * Logger used to report errors. */ private static final Logger logger = Logger.getLogger("Dispatcher"); /** * The target object. */ public final Object object; /** * The target method. */ public final Method method; /** * Create an event dispatcher that calls the given method on the given * object. The method must take a single Event parameter. If a * SecurityException or a NoSuchMethodException occurs when getting the * Method object, then it is logged and wrapped in a RuntimeException and * re-thrown. * * @param object * The target object. * @param method * The method name. * @throws RuntimeException * If a SecurityException or NoSuchMethodException occurs. */ public EventDispatcher(Object object, String method) throws RuntimeException { try { this.object = object; this.method = object.getClass().getMethod(method, Event.class); } catch (SecurityException e) { logger.log(Level.SEVERE, "Cannot get method by reflection", e); throw new RuntimeException(e); } catch (NoSuchMethodException e) { logger.log(Level.SEVERE, "Method not found: " + method, e); throw new RuntimeException(e); } } /** * Invoke the method on the object by reflection. If any exception occurs in * the invocation, it is logged, then wrapped in a RuntimeException and * re-thrown. * * @param event * The event to pass to the method invocation. * * @return The result of the method invocation, or null if the method is * void. * * @throws RuntimeException * If any exception occurs in the invocation, it is wrapped in a * RuntimeException and re-thrown. */ public Object invoke(Event event) throws RuntimeException { try { return method.invoke(object, event); } catch (IllegalArgumentException e) { logger.log(Level.SEVERE, "Error invoking method", e); throw new RuntimeException(e); } catch (IllegalAccessException e) { logger.log(Level.SEVERE, "Error invoking method", e); throw new RuntimeException(e); } catch (InvocationTargetException e) { logger.log(Level.WARNING, "Invocation target error", e); throw new RuntimeException(e); } } /** * Allows the dispatcher to be used as an SWT listener. The event is * passed to the method and the return value is ignored. */ public void handleEvent(Event event) { invoke(event); } }