Gen*_*ene 5 java casting method-reference
在这一点上,JLS 转换规则似乎相当复杂:将对返回某个值的方法的引用转换为接受相同参数类型但返回 的引用是否正确void?我认为这还可以,因为void它比任何类型都窄。
例如...
import java.util.function.Consumer;
public class MethodRefCaster {
/** Operation accepting and returning Integer. */
Integer fooOp(Integer x) {
System.out.println(x);
return x + 3;
}
/** Applier of given op accepting Integer, returning void. */
void applyOpToBar(Consumer<Integer> op, int bar) {
op.accept(bar);
}
public static void main(String [] args) {
MethodRefCaster x = new MethodRefCaster();
// Cast the method ref to make it fit.
x.applyOpToBar((Consumer<Integer>) x::fooOp, 42);
}
}
Run Code Online (Sandbox Code Playgroud)
如您所料,这将打印 42。但这是正确的Java吗?非常感谢。
| 归档时间: |
|
| 查看次数: |
458 次 |
| 最近记录: |