您的问题不太清楚,因为发布的代码中有两种类型转换。
第一个检查通过instanceof
是否Consumer<? super Integer>
也实现IntConsumer
并执行普通类型转换,假设一个类同时实现Consumer
和IntConsumer
将使用相同的语义执行此操作。与文档比较:
实施要求:
如果动作是 的实例,IntConsumer
则将其强制转换为IntConsumer
并传递给 ,否则通过将 的参数装箱,tryAdvance(java.util.function.IntConsumer);
将动作适应于 的实例,然后传递给。IntConsumer
IntConsumer
tryAdvance(java.util.function.IntConsumer)
因此,第一次instanceof
检查和类型转换是合同的第一部分,如果action
参数实现了两个接口,则避免装箱。
The second type cast is part of the described adaptation to a boxing IntConsumer
whereas the boxing is implied by the method reference (IntConsumer) action::accept
. This method reference refers to the method void accept(T t)
(where T := ? super Integer
) which can be adapted to the function signature of IntConsumer
, as described by Brian Goetz. Since this functional signature does not only fulfill the signature of IntConsumer
but also (of course) the signature of Consumer<? super Integer>
the type cast is needed to disambiguate between the overloaded tryAdvance
methods. It would be unnecessary when using the equivalent lambda expression
return tryAdvance((int i)->c.accept(i));