为什么这个程序是用Java7编译的,而不是用Java8编译的?
考虑一下这个计划:为什么这个程序是用Java7编译的,而不是用Java8编译的?,java,javac,jls,Java,Javac,Jls,考虑一下这个计划: public class xx<T> { <T> Iterable<T> createIterable(Class<T> cls) { return null; } Iterable<? extends Number> createNumberIterable(boolean floatingPoint) { return this.createIterab
public class xx<T> {
<T> Iterable<T> createIterable(Class<T> cls) {
return null;
}
Iterable<? extends Number> createNumberIterable(boolean floatingPoint) {
return this.createIterable(floatingPoint ? Integer.class : Float.class);
}
}
在Java 8下,它不:
$ 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<T#2> cannot be applied to given types;
return this.createIterable(floatingPoint ? Integer.class : Float.class);
^
required: Class<T#1>
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 <T#1>createIterable(Class<T#1>)
T#2 extends Object declared in class xx
1 error
$
$java-version
java版本“1.8.0_40”
Java(TM)SE运行时环境(构建1.8.0_40-b25)
Java HotSpot(TM)64位服务器虚拟机(构建25.40-b25,混合模式)
$javac xx.java
xx.java:8:错误:类xx中的方法createIterable无法应用于给定类型;
返回此.createIterable(floatingPoint?Integer.class:Float.class);
^
必修课:课堂
找到:floatingPo[…]类
原因:推断类型不符合相等约束
推断:浮动
相等约束:浮点、整数
其中T#1,T#2是类型变量:
T#1扩展方法createIterable(类)中声明的对象
T#2扩展类xx中声明的对象
1错误
$
这是真的:
(注意:请不要解释如何解决问题,这不是问题)旧的行为既不是错误,新的行为也不是错误。条件表达式类型的规则变得更加复杂,这在很多情况下是有帮助的,但在您的情况下并没有什么坏处
编译器不允许它,因为
Integer.class
和Float.class
的类型是不可比较的。没有类型T
会使Class
成为Class
和Class
的超类型。这里似乎回答了这个问题:尝试解决方法-createIterable(Class
$ 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<T#2> cannot be applied to given types;
return this.createIterable(floatingPoint ? Integer.class : Float.class);
^
required: Class<T#1>
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 <T#1>createIterable(Class<T#1>)
T#2 extends Object declared in class xx
1 error
$