考虑以下两个功能接口( java.lang.Runnable and java.util.concurrent.Callable<V>):
public interface Runnable {
void run();
}
public interface Callable<V> {
V call();
}假设您有overloaded,方法调用如下:
void invoke(Runnable r) {
r.run();
}
<T> T invoke(Callable<T> c) {
return c.call();
}考虑下面的方法调用
String s = invoke(() -> "done");这将调用invoke(Callable)。但是怎么做呢?填充器如何能够将类型确定为可调用类型?我没有从我读过的Oracle文档中理解。
发布于 2019-09-04 09:56:06
因为() -> "done"返回一个字符串值“已完成”,这是Callable的call方法在以下方面所负责的:
String s = invoke(() -> "done");
// from impl. of 'invoke', the variable 's' is assigned value "done"另一方面,run是一个void方法,与Runnable类型匹配的可能是一个空调用,如:
invoke(() -> System.out.println("done"))https://stackoverflow.com/questions/57785855
复制相似问题