簡體   English   中英

使用參數調用對象的非靜態方法引用

[英]Calling non-static method reference on an object with an argument

我正在創建一個事件處理框架,並希望執行以下操作:

// 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::onEventSomeListener::onOtherEvent的形式為“引用任意對象的實例方法” ,其中調用者提供目標實例來調用方法,類似於lambda表達式(l,e) -> l.onEvent(e)(l,e) -> l.onOtherEvent(e) ,這就是目標實例成為第一個功能參數的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM