这与方法引用调用有关,在lambda中,我们能够对具有不同返回类型的方法进行方法引用。参见下面的代码-
interface Sayable {
void say();
}
class SayableImpl implements Sayable {
@Override
public boolean say() {
// error wrong return type
}
}
public class MethodReference {
public static boolean saySomething() {
System.out.println("Hello, this is static method.");
return true;
}
public static void main(String[] args) {
MethodReference methodReference = new MethodReference();
Sayable sayable = () -> methodReference.saySomething();
sayable.say();
// Referring static method
Sayable sayable2 = MethodReference::saySomething;
sayable2.say();
}
}
在这里,我们正在使用say()
实现void MethodReference::saySomething()
的方法,其返回类型为boolean
。
我们如何证明这一点?我想念什么吗?
答案 0 :(得分:1)
因为您还可以编写
class SayableImpl implements Sayable {
@Override
public void say() {
new MethodReference().saySomething();
}
}
这是您最终使用lambda表示时要做的
Sayable sayable = () -> methodReference.saySomething()