我有下面的代码确实产生了预期的结果。有人可以解释窗帘背后发生了什么吗?我不明白编译器/ JVM如何知道需要在Storer对象上调用store(String str)或者它如何定义doSomething(Storer s,String str)实现。
storer.Java
public class Storer {
private List<String> storer = new ArrayList<>();
public void store(String str) {
storer.add(str);
}
@Override
public String toString() {
return "Storer [storer=" + storer + "]";
}
}
my interface.Java
@FunctionalInterface
public interface MyInterface {
public abstract void doSomething(Storer s, String str);
}
executor.Java
public class Executor {
public void doStore(Storer storer, String s, MyInterface p) {
p.doSomething(storer, s);
}
}
test functional interfaces.Java
public class TestFunctionalInterfaces {
public static void main(String[] args) {
Storer storer = new Storer();
Executor test = new Executor();
test.doStore(storer, "I've got added", Storer::store);
System.out.println(storer);
}
}
输出是:
Storer [storer=[I've got added]]
提前致谢。
方法参考Store::storer
相当于lambda (s, str) -> s.store(str)
。通常,给定一个期望args a1,a2,a3,...的函数接口,此类型的方法引用等效于调用a1.namedMethod(a2,a3,...)的lambda。见this answer。
Storer::store
是一种方法参考,可用于代替任何@FunctionalInterface
s。你在这里得到的基本上是My Interface实现的简写。相当于:
public class MyInterfaceImpl implements MyInterface {
public void doSomething(Storer storer, String str) {
storer.store(str);
}
}
这个实现(通过你的方法引用指定)是执行storer.store()的原因...因为你已经指定并传递给你的Executor的MyInterface的实现。编译器足够智能,可以将实现/方法引用与您提供的参数相匹配