您的位置:首页 > 编程语言 > Java开发

jdk8 lambda的方法引用引起的编译器bug

2017-09-30 13:26 561 查看

jdk8 lambda的方法引用引起的编译器bug

当使用
class::method
这种引用方式的时候,如果receiver类有多个super type,在编译的时候没有问题,但是在运行的时候就会异常
Invalid receiver type class...


解决方法是:

改为lambda表达式。

原文:

You ran into the same compiler bug that has been discussed in this question and that >question.

The problem occurs whenever an intersection type is involved and you are using a method >reference using a receiver type other than the first one (the first type is the one that will >remain after type erasure).

So when you replace the method reference with a lambda expression, you are not affected by >the bug anymore. If you remove the Serializable from the types instead, the inferred element >type of the Stream will be Fruit, i.e. not an intersection type, and again the problem does >not occur. But with the two element types implementing Fruit and Serializable, the compiler >will infer the element type Object&Fruit&Serializable and the raw type will be Object which >provokes the error when using a method reference with the receiver type Fruit. You can easily >work around this:

Stream.of(apples.stream(), oranges.stream())

.flatMap(Function.identity())

.map(Fruit::getPickingMonth) // no more exception on this line

.forEachOrdered(System.out::println);

The compiled code will be identical to your original, but the formal result type of the >flatMap operation will be Stream, ignoring all other artifacts of the inferred >intersection type. As a consequence the method reference Fruit::getPickingMonth will >implement the type Function
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: