我創建一個事件處理框架,並想做到以下幾點:調用對象的非靜態方法的參考用的參數
// 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()
方法,以便使用適當的參數從每個偵聽器對象調用它們。有任何想法嗎?
'MethodReference'界面是怎樣的? – Flown
@Flown它實際上並不存在,我只是把它放在那裏以符合Java的語法。我不確定它應該是什麼類型。 – SamTebbs33
爲什麼不[爲搜索](http://docs.oracle.com/javase/8/docs/api/?java/util/function/package-summary.html)獲取適當的界面?所有你需要做的是尋找參數和返回類型... – Holger