如何调用在 Java 中作为参数传递的函数?

How to call a function passed as argument in Java?

好吧,这看起来有点基础,我已经搜索了很多代码以了解代码有什么问题或如何正确执行此操作。我试图简单地使用一个作为参数传递的函数。

import java.util.function.Function;

public class Anonymous {
    public static void main (String[] args) {
        System.out.println("Hi");
    }

    public static void useFunction (Function<Integer, Boolean> fun) {
        boolean a = fun(10);
    }
}

它告诉我 "The method fun(int) is undefined for the type Anonymous".

Function 是具有 apply 方法的功能接口,由于您的函数将 Integer 作为参数并且 returns Boolean,您必须调用 apply 方法通过传递参数

This is a functional interface whose functional method is apply(Object).

boolean a = fun.apply(10);

查看 JavaDoc Function<T, R>. You misinterpret the usage of the function with JavaScript - this is still Java. This interface has a method Function::apply,它将此函数应用于给定参数。

public static void useFunction (Function<Integer, Boolean> fun) {
    boolean a = fun.apply(10);
}