且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以在Java中创建包含多个侦听器类型的自己的事件侦听器列表?

更新时间:2022-12-20 16:17:48

我实现了类似的方法,因为我内心不喜欢Java的EventListenerList。首先,您实现一个通用的侦听器。我根据接收到的事件定义了侦听器,基本上使用了一种方法

I implemented something like this, cause I have a visceral dislike of Java's EventListenerList. First, you implement a generic Listener. I defined the listener based upon the Event it was receiving, with basically one method

interface GenericListener<T extends Event> {
   public void handle(T t);
}

这样可以省去定义ListenerA,ListernerB等的麻烦。用ListenerA,ListenerB等以自己的方式进行操作,它们都扩展了MyListener之类的基础。两种方法都有优缺点。

This saves you having to define ListenerA, ListernerB etc... Though you could do it your way with ListenerA, ListenerB, etc, all extending some base like MyListener. Both ways have plusses and minuses.

然后,我使用 CopyOnWriteArraySet 来容纳所有这些侦听器。设置集是要考虑的原因,因为太松散的编码人员经常将侦听器添加两次。 YMMV。但是,实际上,您有一个 Collection< GenericListener< T扩展Event>>。或Collection< MyListener>

I then used a CopyOnWriteArraySet to hold all these listeners. A set is something to consider cause all too often listeners get added twice by sloppy coders. YMMV. But, effectively you have a Collection<GenericListener<T extends Event>> or a Collection<MyListener>

现在,您已经发现,使用类型擦除,Collection只能容纳一种类型的侦听器。这通常是一个问题。解决方案:使用地图。

Now, as you've discovered, with type erasure, the Collection can only hold one type of listener. That is often a problem. Solution: Use a Map.

由于我将一切都基于事件,因此我使用了

Since I'm basing everything upon the event, I used

Map<Class<T extends Event>, Collection<GenericListener<T extends Event>>>

根据事件的类别,获取要获取该事件的侦听器的列表。 br>
您的替代方法是基于侦听器的类

based upon the class of the event, get the list of listeners who want to get that event.
Your alternative is to base it upon the class of the listener

Map<Class<T extends MyListener>, Collection<MyListener>>

上面可能有一些错别字...

There's probably some typos above...