Advertisement
Guest User

Untitled

a guest
Jun 10th, 2011
458
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.08 KB | None | 0 0
  1. import java.lang.reflect.InvocationHandler;
  2. import java.lang.reflect.InvocationTargetException;
  3. import java.lang.reflect.Method;
  4. import java.lang.reflect.Proxy;
  5. import java.util.ArrayList;
  6. import java.util.EventListener;
  7. import java.util.List;
  8.  
  9. public class Announcer<T extends EventListener> {
  10.     private final T proxy;
  11.     private final List<T> listeners = new ArrayList<T>();
  12.      
  13.      
  14.     public Announcer(Class<? extends T> listenerType) {
  15.         proxy = listenerType.cast(Proxy.newProxyInstance(
  16.             getClass().getClassLoader(),  
  17.             new Class<?>[]{listenerType},  
  18.             new InvocationHandler() {
  19.                 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  20.                     announce(method, args);
  21.                     return null;
  22.                 }
  23.             }));
  24.     }
  25.      
  26.     public void addListener(T listener) {
  27.         listeners.add(listener);
  28.     }
  29.      
  30.     public void removeListener(T listener) {
  31.         listeners.remove(listener);
  32.     }
  33.      
  34.     public T announce() {
  35.         return proxy;
  36.     }
  37.      
  38.     private void announce(Method m, Object[] args) {
  39.         try {
  40.             for (T listener : listeners) {
  41.                 m.invoke(listener, args);
  42.             }
  43.         }
  44.         catch (IllegalAccessException e) {
  45.             throw new IllegalArgumentException("could not invoke listener", e);
  46.         }
  47.         catch (InvocationTargetException e) {
  48.             Throwable cause = e.getCause();
  49.              
  50.             if (cause instanceof RuntimeException) {
  51.                 throw (RuntimeException)cause;
  52.             }  
  53.             else if (cause instanceof Error) {
  54.                 throw (Error)cause;
  55.             }
  56.             else {
  57.                 throw new UnsupportedOperationException("listener threw exception", cause);
  58.             }
  59.         }
  60.     }
  61.      
  62.     public static <T extends EventListener> Announcer<T> to(Class<? extends T> listenerType) {
  63.         return new Announcer<T>(listenerType);
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement