[英]Calling non-static method reference on an object with an argument
I'm creating an event handling framework and would like to do the following: 我正在创建一个事件处理框架,并希望执行以下操作:
// 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);
}
But I'm not sure how to reference the onEvent()
and onOtherEvent()
methods so that they are called from each listener object with the proper argument. 但我不确定如何引用
onEvent()
和onOtherEvent()
方法,以便使用适当的参数从每个侦听器对象调用它们。 Any ideas? 有任何想法吗?
A method reference is just a way to implement a functional interface, so you have to either, define yourself an appropriate interface or search the predefined types for a match. 方法引用只是实现功能接口的一种方式,因此您必须自己定义适当的接口或搜索预定义的类型以进行匹配。
Since your listener method consumes a target listener instance and an event object and doesn't return a value, BiConsumer
is an appropriate type: 由于您的侦听器方法使用目标侦听器实例和事件对象,并且不返回值,因此
BiConsumer
是一种合适的类型:
protected void notifyListeners(BiConsumer<E,T> method, T eventObj) {
for(E listener: listeners)
method.accept(listener, eventObj);
}
The method references SomeListener::onEvent
and SomeListener::onOtherEvent
have the form “Reference to an instance method of an arbitrary object” where the caller provides the target instance to invoke the method on, similar to the lambda expressions (l,e) -> l.onEvent(e)
and (l,e) -> l.onOtherEvent(e)
, which is why the target instance becomes the first functional parameter. 方法引用
SomeListener::onEvent
和SomeListener::onOtherEvent
的形式为“引用任意对象的实例方法” ,其中调用者提供目标实例来调用方法,类似于lambda表达式(l,e) -> l.onEvent(e)
和(l,e) -> l.onOtherEvent(e)
,这就是目标实例成为第一个功能参数的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.