Lambda函数具有无限数量的参数

Arh*_*owk 2 java lambda interface java-8

我试图解决代码中给出的问题.我想要一个能够接受任何函数的lambda表达式

interface ExecuteAnyCode{
    void execute(Object... args);
}

void entry(){
    ExecuteAnyCode a = Math::sin;
    ExecuteAnyCode b = System.out::println;

    a.execute(5);
    b.execute("Hello World")
}
Run Code Online (Sandbox Code Playgroud)

但它让我对传递给功能接口的函数中的参数有误.有没有办法做到这一点?

Sot*_*lis 7

您的功能接口定义了一个接受a的方法Object....无论您使用哪种方法引用作为该功能接口类型的变量的赋值,都必须具有匹配的签名.Math::sin才不是.

该ExecuteAnyCode#execute方法允许您将其作为调用

ref.execute(1, 2, "3", 4, new Something());
Run Code Online (Sandbox Code Playgroud)

如果有的话会怎么做?

ExecuteAnyCode ref = Math::sin;
ref.execute(1, 2, "3", 4, new Something());
Run Code Online (Sandbox Code Playgroud)

什么会被传递给Math.sin?

该语言不允许您尝试做什么.Lambdas和方法引用要求在编译时知道此信息.