它怎麽工作?如何将Consumer<? super Integer>转换为IntConsumer??
default boolean tryAdvance(Consumer<? super Integer> action) {
if (action instanceof IntConsumer) {
return tryAdvance((IntConsumer) action);
}
else {
if (Tripwire.ENABLED)
Tripwire.trip(getClass(),
"{0} calling Spliterator.OfInt.tryAdvance((IntConsumer) action::accept)");
return tryAdvance((IntConsumer) action::accept);
}
}发布于 2015-06-22 08:53:37
您的问题不太清楚,因为在发布的代码中有两种类型的类型转换。
第一个方法通过instanceof检查Consumer<? super Integer>是否也实现了IntConsumer,然后执行普通类型的强制转换,假设同时实现Consumer和IntConsumer的类将具有相同的语义。与文献资料的比较
实现需求: 如果该操作是
IntConsumer的实例,则将其转换为IntConsumer并传递给tryAdvance(java.util.function.IntConsumer);,否则该操作将通过装箱IntConsumer的参数调整为IntConsumer的实例,然后传递给tryAdvance(java.util.function.IntConsumer)。
因此,第一个instanceof检查和类型强制转换是契约的第一部分,如果action参数实现了这两个接口,则避免装箱。
第二种类型强制转换是所描述的对装箱IntConsumer的适应性的一部分,而装箱是由方法参考 (IntConsumer) action::accept暗示的。该方法引用了方法void accept(T t) (其中T := ? super Integer),它可以适应IntConsumer的函数签名,如布赖恩·戈茨。由于这个函数签名不仅完成了IntConsumer的签名,而且(当然)还完成了Consumer<? super Integer>的签名,所以需要类型强制转换来消除重载的tryAdvance方法之间的歧义。当使用等效lambda表达式时,这将是不必要的。
return tryAdvance((int i)->c.accept(i));发布于 2015-06-20 13:35:22
强制转换为绑定方法引用action::accept提供目标类型,该对象类型等效于lambda x -> action.accept(x)。IntConsumer目标类型使这个lambda (它倾向于接受一个整数)被调整为接受一个int (这将导致参数在传递给action.accept()之前被隐式装箱)。
https://stackoverflow.com/questions/30952893
复制相似问题