英文:
How to pass a function as method parameter in java when I can not change the original function
问题
我已经找到了很多关于这个问题的答案,但所有这些答案都说我们首先必须改变函数定义或为函数创建一个接口(或类似的事情)
我的用例是这样的,我正在扩展一个外部的 Plugin
类,该类有一个受保护的方法 notifyListeners
/**
* 通知所有监听器事件已发生
* 这将调用带有 retainUntilConsumed 设置为 false 的 {@link Plugin#notifyListeners(String, JSObject, boolean)}
* @param eventName
* @param data
*/
protected void notifyListeners(String eventName, JSObject data) {
notifyListeners(eventName, data, false);
}
我在另一个类中有一个函数,这个函数做一些工作,根据其性质,无法返回最终值(我无法更改此内容),因此我想将 notifyListeners
(this::notifyListeners
) 作为参数传递到该类函数中,但我找不到如何定义它。我尝试过使用 Function<T, R>
,但它不接受 void 作为返回参数。
这种情况可能吗?
英文:
I have found a lot of answers about this question but all of them says that we have to first change the function definition or create an interface for the function (or similar things)
My use case is this, I am extending an external Plugin
class that has a protected method notifyListeners
/**
* Notify all listeners that an event occurred
* This calls {@link Plugin#notifyListeners(String, JSObject, boolean)}
* with retainUntilConsumed set to false
* @param eventName
* @param data
*/
protected void notifyListeners(String eventName, JSObject data) {
notifyListeners(eventName, data, false);
}
I have a function in another class that does some work that for the nature of it, can not return the end value (I can not change this) so I want to take notifyListeners
(this:: notifyListeners
) as a parameter into that class function but I can not find how to define that. I tried with Function<T, R>
but it does not take void as a return parameter.
Is this possible?
答案1
得分: 2
是的,这是可能的。您可以使用BiConsumer接口来实现此目的。
英文:
Yes, it's possible. You can use the BiConsumer Interface for this purpose.
答案2
得分: 1
BiConsumer<String, JSObject>
英文:
BiConsumer<String, JSObject>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论