使用参数调用对象的非静态方法引用

时间:2016-01-29 16:27:49

标签: java events event-handling java-8

我正在创建一个事件处理框架,并希望执行以下操作:

// 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()方法,以便使用正确的参数从每个侦听器对象调用它们。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

方法引用只是实现功能接口的一种方式,因此您必须为自己定义适当的接口或search the predefined types进行匹配。

由于您的侦听器方法使用目标侦听器实例和事件对象,并且未返回值,因此BiConsumer是合适的类型:

protected void notifyListeners(BiConsumer<E,T> method, T eventObj) {
    for(E listener: listeners)
        method.accept(listener, eventObj);
}

方法引用SomeListener::onEventSomeListener::onOtherEvent具有“Reference to an instance method of an arbitrary object”形式,其中调用者提供目标实例以调用方法,类似于lambda表达式(l,e) -> l.onEvent(e)和{ {1}},这就是目标实例成为第一个功能参数的原因。