如何在Java中将函数作为方法参数传递,当我无法更改原始函数。

huangapple go评论75阅读模式
英文:

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&lt;T, R&gt; 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>

huangapple
  • 本文由 发表于 2020年10月4日 04:22:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/64188640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定