1

我很好奇应该使用哪种方法从 EventListenerList 中检索侦听器列表。Oracle 文档示例显示 getListenerList ,然后在 fireXXXEvent 方法中向后遍历它,但我想知道 getListeners 是否会是更好的选择?

     listeners = listenerList.getListenerList();
     for (int i = listeners.length - 2; i >= 0; i -= 2)

或者

     listeners = listenerList.getListeners(ListenerClass.class);
     for (ListenerClass listener : listeners) {
4

1 回答 1

1

If all your Listeners are of a single, known class, the second form is much simpler and less prone to error. If you have maybe two types of listeners, use the second form twice.

If you have a mish-mash of listeners of different classes, use the first form, which IMO is some of the ugliest, grossest, hackiest, least Object Oriented code ever written.

p.s. IMO (admittedly biased cause I really dislike the EventListenerList implementation) you should consider writing your own EventListenerList class using a CopyOnWriteArrayList or CopyOnWriteArraySet, which are ideally suited for this task.

于 2013-03-05T16:39:40.180 回答