供应商作为一个函数



下面是如何工作的?在需要Function的地方,我传递了一个Supplier

class Scratch {
private Bar bar = new Bar("foo");
public static void main(String[] args) {
Scratch scratch = new Scratch();
System.out.println(scratch.getBarValue(Bar::getValue));
}
public <T> T getBarValue(Function<Bar, T> extractor) {
return extractor.apply(bar);
}
static class Bar {
private String value;
Bar(String value) {
this.value = value;
}
String getValue() {
return value;
}
}
}

我知道Java正在从供应商创建一个函数,但奇怪的是找不到任何相关的文档。

getValue()似乎没有参数,但它实际上有一个隐式的this参数。

通常都隐藏在object.method(...)的语法糖后面。但是,当使用::创建方法引用时,隐式的this就变得显式了。然后,getValue()被视为一个单参数函数,因为只有当它知道它被调用的Bar是什么时,它才能被调用。

这种情况发生在任何实例方法中。它不适用于static方法;他们没有this

Bar::getValue是一个接受Bar实例并返回字符串的函数。它不是一个供应商,因为没有Bar实例,它就不能被调用。

给定一个特定的实例,bar::getValue是一个供应商,因为它只从Bar的特定实例中获取值。但是Bar::getValue需要给定Bar的实例,以便在其上调用getValue()。这是Function<Bar, String>