2016-01-29 19 views
1

我創建一個事件處理框架,並想做到以下幾點:調用對象的非靜態方法的參考用的參數

// 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()方法,以便使用適當的參數從每個偵聽器對象調用它們。有任何想法嗎?

+0

'MethodReference'界面是怎樣的? – Flown

+0

@Flown它實際上並不存在,我只是把它放在那裏以符合Java的語法。我不確定它應該是什麼類型。 – SamTebbs33

+3

爲什麼不[爲搜索](http://docs.oracle.com/javase/8/docs/api/?java/util/function/package-summary.html)獲取適當的界面?所有你需要做的是尋找參數和返回類型... – Holger

回答

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)(l,e) -> l.onOtherEvent(e),這就是目標實例成爲第一個功能參數的原因。

+0

完美,謝謝! – SamTebbs33

相關問題