2010-10-18 61 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); 
    } 
}