我正在创建一个事件处理框架,并想执行以下操作:
// E: event listener interface, T: event class
class EventManager<E, T> {
ArrayList<E> listeners = new ArrayList<E>();
// `method` is some sort of reference to the method to call on each listener. There is no `MethodReference` type, I just put it there as I'm not sure what type should be in its place
protected void notifyListeners(MethodReference method, T eventObj) {
for (E listener : listeners) // call `method` from `listener` with `eventObj` as an argument
}
}
class SpecialisedEventManager extends EventManager<SomeListener, SomeEvent> {
// Some method that would want to notify the listeners
public void foo() {
...
// I would like onEvent() to be called from each listener with new SomeEvent() as the argument
notifyListeners(SomeListener::onEvent, new SomeEvent());
...
}
// Some other method that would want to notify the listeners
public void bar() {
...
notifyListeners(SomeListener::onOtherEvent, new SomeEvent());
...
}
}
interface SomeListener {
public void onEvent(SomeEvent event);
public void onOtherEvent(SomeEvent event);
}
但我不确定如何引用 onEvent()
和 onOtherEvent()
方法,以便使用正确的参数从每个侦听器对象调用它们。有什么想法吗?
方法引用只是实现函数接口的一种方式,因此您必须为自己定义一个合适的接口或搜索预定义的类型以查找匹配项。
由于侦听器方法使用目标侦听器实例和事件对象,并且不返回值,因此BiConsumer
是合适的类型:
protected void notifyListeners(BiConsumer<E,T> method, T eventObj) {
for(E listener: listeners)
method.accept(listener, eventObj);
}
该方法引用SomeListener::onEvent
和SomeListener::onOtherEvent
具有"引用任意对象的实例方法"的形式,其中调用方提供目标实例以调用该方法,类似于 lambda 表达式 (l,e) -> l.onEvent(e)
和 (l,e) -> l.onOtherEvent(e)
,这就是目标实例成为第一个功能参数的原因。