java-自定义功能接口作为方法参数
作者:互联网
我下面的代码确实产生预期的结果.有人可以解释幕后发生的事情吗?我不明白编译器/ 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 + "]";
}
}
MyInterface.java
@FunctionalInterface
public interface MyInterface {
public abstract void doSomething(Storer s, String str);
}
执行程序
public class Executor {
public void doStore(Storer storer, String s, MyInterface p) {
p.doSomething(storer, s);
}
}
TestFunctionalInterfaces.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)->商店(str).通常,给定一个期望参数为a1,a2,a3,…的功能接口,此类型的方法引用等效于调用a1.namedMethod(a2,a3,…)的lambda.参见this answer.
标签:functional-interface,java 来源: https://codeday.me/bug/20191024/1922998.html