简体   繁体   English

Java在原始类型上使用instanceof方法产生编译器错误

[英]Java using instanceof method on primitive type gives compiler error

I am learning Java, and I do not understand why the following code does not compile without error: 我正在学习Java,但我不明白为什么下面的代码没有正确编译:

public class SecondClass{

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

Why do I get an error in my conditional operation? 为什么我的条件操作出现错误? The instanceof should return true or false right? instanceof应该返回true还是false In this case there should be false since number is an int , but this code does not compile. 在这种情况下,应该为false因为number是一个int ,但是此代码无法编译。

From section 15.20.2 of the JLS : JLS的15.20.2节开始

The type of the RelationalExpression operand of the instanceof operator must be a reference type or the null type; instanceof运算符的RelationalExpression操作数的类型必须是引用类型或null类型; otherwise, a compile-time error occurs. 否则,将发生编译时错误。

In your case, the case of the RelationalExpression operand is int , therefore you get a compile-time error. 在您的情况下,RelationalExpression操作数的情况是int ,因此您会遇到编译时错误。

Even if you had an expression of type Integer , you'd then run into: 即使您具有类型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. 如果将RelationalExpression对ReferenceType的强制转换(第15.16节)作为编译时错误,则关系表达式的instanceof同样会产生编译时错误。 In such a situation, the result of the instanceof expression could never be true. 在这种情况下, instanceof表达式的结果永远不可能为真。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM