【发布时间】:2019-09-22 06:37:33
【问题描述】:
为什么将一个参数的方法引用作为预期类型BiConsumer 的抽象方法需要两个参数的参数传递是合法的?
例子:
class Experiment {
private String name;
public Experiment(String name) {
this.name = name;
}
public void oneParamMethod(Object o) {
System.out.println(this.name + " and " + o);
}
public <T, S> void executeBiConsumer(BiConsumer<T, S> biCon, T in1, S in2) {
biCon.accept(in1, in2);
}
public static void main(String[] args) {
// notice that the name is "INSTANCE", but it won't be printed out
Experiment exp = new Experiment("INSTANCE");
// executeBiConsumer expects a functional of two params but is given a method
// reference of one param. HOW IS THIS LEGAL?
exp.executeBiConsumer(Experiment::oneParamMethod, new Experiment("PARAM"), 999);
}
}
输出:
PARAM and 999
让我们更改调用,使第二个参数不是Experiment 的实例,如下所示:
exp.executeBiConsumer(Experiment::oneParamMethod, new String("INVALID"), 999);
现在,它不会编译。
- 为什么如果第二个参数是
Experiment实例,代码编译时不会报错,否则为什么编译不出来? - 为什么将只有一个参数的方法引用作为需要
BiConsumer的参数传递是有效的?
【问题讨论】:
标签: java java-8 this method-reference functional-interface