假设我有以下代码:
class proba {
boolean fun(Number n) {
return n == null || 0 == n;
}
}
使用 openjdk 7 (debian wheezy) 编译没有问题,但使用 openjdk 8 时编译失败,并出现以下错误(即使使用 -source 7):
proba.java:3: error: incomparable types: int and Number
return n == null || 0 == n;
^
1 error
如何解决这个问题:
- 此构造是否有编译器选项以继续在 Java 8 中工作?
- 我是否应该使用 instanceof 检查 Number 的所有子类和强制转换,然后逐个进行比较?这看起来很丑……
- 其他建议?
最佳答案
这实际上是一个错误修正(参见 JDK-8013357 ):Java-7 的行为与 JLS §15.21 相矛盾:
The equality operators may be used to compare two operands that are convertible (§5.1.8) to numeric type, or two operands of type
boolean
orBoolean
, or two operands that are each of either reference type or thenull
type. All other cases result in a compile-time error.
在您的情况下,一个操作数是数字类型,而另一个是引用类型(Number
不可转换为数字类型),因此根据规范,它应该是一个编译时错误。
此更改在 Compatibility Guide for Java 8 中提到(搜索“原始”)。
请注意,虽然您的代码在 Java-7 中编译,但它的工作方式有些奇怪:
System.out.println(new proba().fun(0)); // compiles, prints true
System.out.println(new proba().fun(0.0)); // compiles, prints false
System.out.println(new proba().fun(new Integer(0))); // compiles, prints false
这就是为什么 Java-7 将 0 提升为 Integer
对象(通过自动装箱),然后通过引用比较两个对象,这不太可能是您想要的。
要修复您的代码,您可以将 Number
转换为一些预定义的基本类型,例如 double
:
boolean fun(Number n) {
return n == null || 0 == n.doubleValue();
}
关于java - 无与伦比的类型 : int and Number in java 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34858024/