Created
July 24, 2015 17:26
-
-
Save takawitter/4e2759aa667b5f53ec5e to your computer and use it in GitHub Desktop.
Typed and easily to fire event, EventListenerList
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.InvocationHandler; | |
import java.lang.reflect.Method; | |
import java.lang.reflect.Proxy; | |
import java.util.EventListener; | |
public class EventListenerList<T extends EventListener> extends javax.swing.event.EventListenerList{ | |
public EventListenerList(Class<T> clazz){ | |
this.clazz = clazz; | |
this.fireProxy = clazz.cast(Proxy.newProxyInstance( | |
Thread.currentThread().getContextClassLoader(), | |
new Class<?>[]{clazz}, | |
new InvocationHandler() { | |
@Override | |
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { | |
for(T l : getListeners(EventListenerList.this.clazz)){ | |
method.invoke(l, args); | |
} | |
return null; | |
} | |
})); | |
} | |
public void add(T listener){ | |
super.add(clazz, listener); | |
} | |
public void remove(T listener){ | |
super.remove(clazz, listener); | |
} | |
public T fire(){ | |
return fireProxy; | |
} | |
private Class<T> clazz; | |
private transient T fireProxy; | |
private static final long serialVersionUID = -1180452197413107628L; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.EventListener; | |
import java.util.concurrent.atomic.AtomicInteger; | |
import org.junit.Assert; | |
import org.junit.Test; | |
public class EventLIstenerListTest { | |
interface Listener extends EventListener{ | |
void onEvent(int value); | |
} | |
@Test | |
public void test(){ | |
EventListenerList<Listener> listeners = new EventListenerList<>(Listener.class); | |
final AtomicInteger val = new AtomicInteger(0); | |
listeners.add(new Listener(){ | |
@Override | |
public void onEvent(int value) { | |
val.set(value); | |
} | |
}); | |
listeners.fire().onEvent(100); | |
Assert.assertEquals(100, val.get()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment