所以我早些时候做了一些编码,发现一个函数的签名只需要 Function<FooClass, String>
,我可以为生成字符串的 FooClass 函数传递一个方法(参见下面的示例)。
所以我发现这是由 java 支持的,我的意思是..它可以编译,而且我找到了一篇文章 describing the feature here
public static class Foo {
public String produceString() {
return "Hello world!";
}
}
public static String test(Function<Foo, String> produceString) {
return produceString.apply(new Foo());
}
public static void main(String[] args) {
// WEIRD CODE BELOW!! Here's the method reference:
String output = test(Foo::produceString);
System.out.println(output);
// Outputs "Hello world!"
}
我的问题是:java 到底是怎么做到的!?
有人能解释为什么这是有效的吗?
最佳答案
您可以将方法引用视为创建相应 lambda 表达式的语法糖:
String output = test(Foo::produceString);
给定produceString
是一个实例方法,上面的表达式等价于
String output = test( (Foo foo) -> foo.produceString() );
关于java - 为什么实例方法引用适用于不匹配的签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57404152/