Java:像在 JavaScript 中一样将函数作为参数传递?

use*_*170 3 java

我正在尝试编写一个函数,因此我可以将函数作为参数传递,例如

public class HashFunction {
    private Function f;
    public HashFunction(Function f) {
        this.f=f;
    }
    public Integer hash(String s){
        return f(s);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我可以写代码

new HashFunction(function(String s){ return s.charAt(0)+0; });
Run Code Online (Sandbox Code Playgroud)

就像在 javascript 中一样。我怎样才能做到这一点?

Boh*_*ian 5

与许多其他现代语言不同,目前 java 在语法上不支持“浮动代码块”(称为闭包)。

然而,这个概念可以通过使用匿名类来实现,匿名类是“动态”实现声明,通常实现一个接口,但也可以扩展一个类。


以下是在 Java 中编写示例的方法:

public interface Hasher {
    int getHash(String s);
}

public class HashFunction {
    private Hasher f;
    public HashFunction(Hasher f) {
        this.f=f;
    }
    public Integer hash(String s){
        return f(s);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用:

new HashFunction(new Hasher() {
    public int getHash(String s) {return s.charAt(0)+0;}
});
Run Code Online (Sandbox Code Playgroud)