【发布时间】:2019-08-08 01:39:59
【问题描述】:
所以我早些时候做了一些编码,发现一个函数的签名只接受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到底是怎么做到的!?
有没有人解释一下为什么这行得通?
【问题讨论】:
-
它不接受一个字符串,它产生一个字符串,正如它的名字所暗示的那样。它需要一个 Foo 的实例。
-
@shmosel 啊,好电话,更新了描述
标签: java java-8 method-reference