java8不兼容java7,为什么该程序可以用Java 7而不是Java 8编译?

Consider this program:

public class xx {

Iterable createIterable(Class cls) {

return null;

}

Iterable extends Number> createNumberIterable(boolean floatingPoint) {

return this.createIterable(floatingPoint ? Integer.class : Float.class);

}

}

Under Java 7 it compiles:

$ java -version

java version "1.7.0_45"

Java(TM) SE Runtime Environment (build 1.7.0_45-b18)

Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode)

$ javac xx.java

$

Under Java 8 it does not:

$ java -version

java version "1.8.0_40"

Java(TM) SE Runtime Environment (build 1.8.0_40-b25)

Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode)

$ javac xx.java

xx.java:8: error: method createIterable in class xx cannot be applied to given types;

return this.createIterable(floatingPoint ? Integer.class : Float.class);

^

required: Class

found: floatingPo[...]class

reason: inferred type does not conform to equality constraint(s)

inferred: Float

equality constraints(s): Float,Integer

where T#1,T#2 are type-variables:

T#1 extends Object declared in method createIterable(Class)

T#2 extends Object declared in class xx

1 error

$

And which is true:

This is bug in Java 7 that got fixed in Java 8 (compiler was too permissive); or

This is a new bug that was introduced in Java 8

If the answer is #1, can you explain in normal language the reason why the JLS doesn't allow this, using the obvious interpretation?

(Note: please don't explain how to workaround the problem, that's not the question)

解决方案

Neither was the old behavior a bug, nor is the new behavior a bug. The rules for the type of the conditional expression just got more complex, which helps in many cases and doesn't really hurt in yours.

The compiler does not allow it because the types of Integer.class and Float.class are incomparable. There is no type T which would make Class a supertype of both Class and Class.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值