Java 在原始类型上使用 instanceof 方法会导致编译器错误

Java using instanceof method on primitive type gives compiler error

我正在学习Java,我不明白为什么下面的代码不能正常编译:

public class SecondClass{

public static void main(String[] args){
    int number = 45;
    if (number instanceof String) {
        System.out.println("Not a String!");
    }
  }
}

为什么我的条件运算会出错? instanceof 应该 return true 还是 false 对吧?在这种情况下,应该有 false,因为 number 是一个 int,但此代码无法编译。

来自section 15.20.2 of the JLS

The type of the RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs.

在你的例子中,RelationalExpression 操作数的大小写是 int,因此你会得到一个编译时错误。

即使你有一个 Integer 类型的表达式,你也会 运行 变成:

If a cast (§15.16) of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.