package ie.dcu.swt; import java.io.Serializable; import java.lang.reflect.*; import java.util.logging.*; import org.eclipse.swt.widgets.*; /** * Dispatch simple method calls by reflection. * * @author Kevin McGuinness */ public class Dispatcher implements Serializable, Listener { /** * Serialization UID */ private static final long serialVersionUID = -8518627659417915880L; /** * 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 a dispatcher that calls the given method on the given object. The * method should have no parameters. 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 Dispatcher(Object object, String method) throws RuntimeException { try { this.object = object; this.method = object.getClass().getMethod(method); } 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. * * @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() { try { return method.invoke(object); } 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 and * return value are ignored. */ public void handleEvent(Event event) { invoke(); } }