New to Java - Custom EventHandlers
In this sample(it's from the Oracle Site) :
// Notify all listeners that have registered interest for
// notification on this event type. The event instance
// is lazily created using the parameters passed into
// the fire method.
protected void fireFooXXX() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==FooListener.cl开发者_StackOverflow社区ass) {
// Lazily create the event:
if (fooEvent == null)
fooEvent = new FooEvent(this);
((FooListener)listeners[i+1]).fooXXX(fooEvent);
}
}
}
What does this
listeners[i]==FooListener.class
Comparison do? It throws me off a bit, since it seems its comparing an instance of a class to a type of class. I would could understand it if it said something like
listeners[i].getClass() == Foolistener.class
But it doesn't...Can someone enlighten me here? Thanks in advance!
Because that's what the documentation of getListenerList() says it does.
public Object[] getListenerList()
Passes back the event listener list as an array of ListenerType-listener pairs. Note that for performance reasons, this implementation passes back the actual data structure in which the listener data is stored internally! This method is guaranteed to pass back a non-null array, so that no null-checking is required in fire methods. A zero-length array of Object should be returned if there are currently no listeners. WARNING!!! Absolutely NO modification of the data contained in this array should be made -- if any such manipulation is necessary, it should be done on a copy of the array returned rather than the array itself.
The array is in pairs of Type and Instance. So index zero is the class (or superclass) of the actual listener found at index 1, index 2 is the class of the actual listener at 3, etc.
It looks like their array alternates between Class
objects and FooListener
objects.
For any n
, listeners[2n]
will contain a Class
instance, and listeners[2n + 1]
will contain a FooListener
instance for that class.
I'm going to go the complete side-route and suggest not using EventListenerList
. It's a terrible bit of code that is only useful if you are either in java 1.4 or earlier or you are using one list to hold listeners for several different listener classes.
I'd recommend instead using a List<FooListener>
for your listener holder. You can still do the same stuff that EventListenerList
allows, but your code will be easier to follow.
private final List<FooListener> myFooListeners;
...
void fireXXX() {
FooEvent event = ....
for (FooListener fl : myFooListeners) {
fl.xxx(event);
}
}
精彩评论