如何在Java 8中间接运行方法引用? [英] How to indirectly run a method reference in Java 8?

查看:119
本文介绍了如何在Java 8中间接运行方法引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般问题是:


  • 使用语法 object :: aMethod ,是否可以转换为 MethodHandle 这样的类型作为功能接口?

  • 如果不是,方法引用怎么样?如果可能的话,在Java 8中间接调用?

  • When using the syntax object::aMethod, can it be converted to a type such as MethodHandle as a functional interface?
  • If no, how can a method reference be indirectly invoked in Java 8 if at all possible?

作为一个例子,假设我们想要一个 MethodRefRunner as:

As an example, imagine we'd like to have a MethodRefRunner as:

class MethodRefRunner {
  static void execute(Object target, WHATTYPE mref, Object... args) {
    mref.apply(args);
  }
}

它可以用作: MethodRefRunner.execute(o,o :: someMethod,someParam)

在上面的代码片段中, WHATTYPE 是 java.util.function.Function 但非常严格。正如此答案所述,在版本b75之前,有一个 java.util.function.Block 可用并且可能很方便。

In the above snippet, one option for WHATTYPE is java.util.function.Function but very restrictive. As this answer mentions, prior to version b75, there was a java.util.function.Block was available and might be handy.

另一方面,任何机会 WHATTYPE 可以某种方式转换为 java.lang.invoke.MethodHandle

On the other side, any chance that WHATTYPE could be in some way converted to a java.lang.invoke.MethodHandle?

注意给Java专家:请根据需要细化问题的标题。

Note to Java experts: Please refine the title of the questions as needed.

推荐答案

我认为没有办法做你想做的事。 WHATTYPE必须是一个功能界面—不一定是 Function ,但其单个抽象方法匹配 somemethod 。它是一种普通的接口类型,遵循管理Java类型的通常规则。 java.util.function.Block 是这样的普通接口类型,并不像你想象的那样特别。 (顺便说一句,它现在仍在,消费者。)

I don't think there is any way to do what you want. WHATTYPE is going to have to be a functional interface—not necessarily Function, but one whose single abstract method matches somemethod. It's an ordinary interface type, subject to the usual rules governing Java types. java.util.function.Block was an ordinary interface type like this, and not special in the way that you seem to think. (It's still around, by the way, now called Consumer.)

这篇关于如何在Java 8中间接运行方法引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆