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

问题描述 投票:1回答:1

我的代码是这样的,

@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方法参考。

java java-8 method-reference functional-interface
1个回答
0
投票

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


代码行

MathOperation2 mo2 = Method_reference_demo::operate2

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

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

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

注意,如果您更改签名以删除最后一个参数,则可以使用此方法,但这将使其效率低下,因为最好定义一个遵循相同签名的接口本身的抽象方法。


除这两行外,我无法更改任何代码行

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

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'
© www.soinside.com 2019 - 2024. All rights reserved.