java - 如何在 Java 8 的 Method_reference 中为用户定义的接口(interface)和方法传递参数

标签 java java-8 method-reference functional-interface

我的代码是这样的,

@FunctionalInterface
interface MathOperation2 {
    int operation2(int a, int b, int c);
 }

public class Method_reference_demo {
    private static int operate2(int a, int b, int c, MathOperation2 obj) 
    { 
        return obj.operation2(a, b, c);
    }
    private void Method_reference_demo01() 
    {       
    MathOperation2 mo2 = Method_reference_demo::operate2;
    mo2.operation2(2,3,4);
    }
}

无论如何我可以通过最后两行传递参数来使其工作。 表示线下。 MathOperation2 mo2 = Method_reference_demo::operate2; mo2.operation2(2,3,4); 我想要上面的代码片段作为工作代码。
注意:除了这两行之外,我无法更改任何代码行,并且想使用 Java 8 方法引用。

最佳答案

底线:- 您需要在某个时间点提供接口(interface)的实现才能使用它。


代码行

MathOperation2 mo2 = Method_reference_demo::operate2

在无效的声明中,因为 operate2 方法的签名

int operate2(int a, int b, int c, MathOperation2 obj)

期望 MathOperation2 也被传递给该方法。

请注意,如果您更改签名以删除最后一个参数,它可以工作,但这会降低效率,因为最好定义接口(interface)本身的抽象方法,它遵循相同的签名。


I can't change any line of code except these two lines

然后您可以将您的界面定义为:

MathOperation2 mo2 = (a, b, c) -> {
    return 0; // perform the operation with a, b and c here
};
System.out.println(mo2.operation2(2, 3, 4)); // just to print the output

例如,要将三个整数相加,表示形式为:

MathOperation2 mo2 = (a, b, c) -> a + b + c;
System.out.println(mo2.operation2(2, 3, 4)); // would print '9'

(来自评论)就方法引用而言,该示例将转化为以下内容:

private static int operate2(int a, int b, int c) { // <<-- notice the method signature
    return a + b + c; // <<--  and a definition
}

private void Method_reference_demo01() {
    MathOperation2 mo2 = Method_reference_demo::operate2;
    System.out.println(mo2.operation2(2, 3, 4)); // prints '9'
}

关于java - 如何在 Java 8 的 Method_reference 中为用户定义的接口(interface)和方法传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58338891/

相关文章:

java - 在 Play Framework 中将字符串转换为 Html

java - 发生了什么样的异常?

java - http连接池如何在 Jersey 工作?

JavaFX WebView 不加载页面

java - 热衷于将方法引用运算符与嵌套方法一起使用?

java - 实例方法引用。没有找到合适的方法

java - 货币实用程序 Java 错误代码 'int java.lang.Object.hashCode()'

java - ResourceBundle - 属性文件继承

java - 如何将对象映射到字符串中以使用 ObjectMapper 进行设置

java - 有没有一种方法可以使用方法引用进行降序排序?