gpt4 book ai didi

java - BiConsumer和一个参数的方法引用

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:44:04 31 4
gpt4 key购买 nike

<分区>

为什么将一个参数的方法引用作为预期类型 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);

现在,它不会编译。


  1. 如果第二个参数是 Experiment 实例,为什么代码编译没有报错,否则为什么不能编译?
  2. 为什么将只有一个参数的方法引用作为期望 BiConsumer 的参数传递是有效的?

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com