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

来源:互联网 发布:郭靖 杨过 知乎 编辑:程序博客网 时间:2024/05/22 08:23

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

原创粉丝点击