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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值