Java 如何知道要使用 lambda 表达式调用哪个重载方法?(供应商、消费者、可呼叫等)
首先,我不知道如何体面地表达这个问题,所以这是有待建议的。
假设我们有以下重载方法:
void execute(Callable<Void> callable) {
try {
callable.call();
} catch (Exception e) {
e.printStackTrace();
}
}
<T> T execute(Supplier<T> supplier) {
return supplier.get();
}
void execute(Runnable runnable) {
runnable.run();
}
从这张桌子上走开,我从另一个SO问题中得到了
Supplier () -> x
Consumer x -> ()
BiConsumer x, y -> ()
Callable () -> x throws ex
Runnable () -> ()
Function x -> y
BiFunction x,y -> z
Predicate x -> boolean
UnaryOperator x1 -> x2
BinaryOperator x1,x2 -> x3
这些是我在本地得到的结果:
// Runnable -> expected as this is a plain void
execute(() -> System.out.println());
// Callable -> why is it not a Supplier? It does not throw any exceptions..
execute(() -> null);
// Supplier -> this returns an Object, but how is that different from returning null?
execute(() -> new Object());
// Callable -> because it can throw an exception, right?
execute(() -> {throw new Exception();});
编译器如何知道要调用哪个方法?例如,它如何区分什么是a和什么是a?Callable
Runnable