So I was doing some coding earlier and discovered that a function that has a signature that just takes Function<FooClass, String>
, I can pass a method for a function of FooClass that produces a String (see example below).
So I've discovered that this is supported by java, I mean.. it compiles, and I've found an article 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!"
}
My question is this: how the hell does java do this!?
Does anyone have an explanation for why this works?
You may treat Method Reference as syntactic sugar for create corresponding lambda expression:
String output = test(Foo::produceString);
given produceString
is an instance method, above expression is equivalent to
String output = test( (Foo foo) -> foo.produceString() );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.