2010-10-18 60 views
2

在此示例中(这是从Oracle Site):新到Java - 自定义事件处理

// 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.class) { 
     // Lazily create the event: 
     if (fooEvent == null) 
      fooEvent = new FooEvent(this); 
     ((FooListener)listeners[i+1]).fooXXX(fooEvent); 
    } 
} 
} 

这是什么

听众[I] == FooListener.class

比较呢?它引发了我一些,因为它似乎将一个类的实例与一个类的类型进行比较。我如果说像

听众[I] .getClass()== Foolistener.class

但它不...可有人开导我在这里将能够理解吗?提前致谢!

回答

1

因为这就是getListenerList()的文档所说的。

公共对象[] getListenerList()

形式传回事件侦听器列表作为 ListenerType侦听 对阵列。请注意,对于性能 的原因,此实现将 传回 的实际数据结构,其中听众数据在内部存储为 !这种方法保证 传回一个非空数组,因此 在火 方法中不需要空值检查。如果 目前没有侦听器,则应返回对象 的零长度数组。警告!!! 绝对没有修改这个数组中包含的数据 应该是 - 如果需要这样的操作,它应该在返回数组的拷贝 上完成,而不是 数组本身。

该数组是成对的Type和Instance。因此,索引零是在索引1处找到的实际侦听器的类(或超类),索引2是在3处的实际侦听器的类等。

+0

对,所以它比较类型(在数组中)类... make的意义。 因此,如果我在数组中使用奇数并使用侦听器[i] .getClass()== FooListener.class,它会执行相同的操作吗? – Rene 2010-10-18 22:28:03

+0

@Rene:是的,会的。 – SLaks 2010-10-18 22:31:34

+0

不一定。添加它们时,指定它们将被“计数”为的侦听器的类型。索引为1的对象的具体类型实际上可能是索引为0的类的子类。 – Affe 2010-10-18 22:34:45

0

看起来像他们的数组在Class对象和FooListener对象之间交替。

对于任何nlisteners[2n]将包含Class实例,listeners[2n + 1]将包含一个FooListener实例为类。

0

我要去完整的旁路并建议不使用EventListenerList。这是一个很糟糕的代码,只有在您使用java 1.4或更早版本时才有用,或者您使用一个列表来保存多个不同监听器类的侦听器。

我建议改为使用List<FooListener>作为听众。你仍然可以做与EventListenerList允许的一样的东西,但是你的代码会更容易遵循。

private final List<FooListener> myFooListeners; 
... 
void fireXXX() { 
    FooEvent event = .... 
    for (FooListener fl : myFooListeners) { 
    fl.xxx(event); 
    } 
}