Instanceof 语法错误?

Instanceof syntax error?

我有一个与“instanceof”相关的练习,但我不太确定如何使用它。这就是我想出的:

for(int i = 4; i < 6; i++){
    int availSupply = part[i].stockLevel+part[i].getAvailForAssembly();
    if(availSupply instanceof Integer){
        System.out.println("Total number of items that can be supplied for "+ part[i].getID()+"(" + part[i].getName() + ": "+ availSupply);
    }
}

代码对我来说看起来不错,但是出现错误:

Multiple markers at this line

Incompatible conditional operand types int and Integer at:  if(availSupply instanceof Integer){

我不知道我做错了什么,这是出现的唯一错误。

您不能将 instanceof 与原始类型的表达式一起使用,就像您在此处对 availSupply 所做的那样。毕竟,int 不可能是其他任何东西。

如果 getAvailForAssembly() 已经声明为 return int,那么您根本不需要 if 语句 - 只需无条件执行正文。如果它 returns Integer,你应该使用:

Integer availSupply = ...;
if (availSupply != null) {
    ...
}

此处 int 是原始值,instanceof 关键字检查对象属于 class 在您的情况下,即 Integer.so int它本身是一个原始值它不是 class Integerinstance 下面是 instanceof 关键字的基本片段,介绍了它的用法。

class InstanceofDemo {
    public static void main(String[] args) {

        Parent obj1 = new Parent();
        Parent obj2 = new Child();

        System.out.println("obj1 instanceof Parent: "
            + (obj1 instanceof Parent));
        System.out.println("obj1 instanceof Child: "
            + (obj1 instanceof Child));
        System.out.println("obj1 instanceof MyInterface: "
            + (obj1 instanceof MyInterface));
        System.out.println("obj2 instanceof Parent: "
            + (obj2 instanceof Parent));
        System.out.println("obj2 instanceof Child: "
            + (obj2 instanceof Child));
        System.out.println("obj2 instanceof MyInterface: "
            + (obj2 instanceof MyInterface));
    }
}

class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {}

输出:

 obj1 instanceof Parent: true
   obj1 instanceof Child: false
   obj1 instanceof MyInterface: false
    obj2 instanceof Parent: true
    obj2 instanceof Child: true
    obj2 instanceof MyInterface: true

请仔细阅读此 link 以更好地理解 instanceof 关键字: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

您不能对基本类型的变量(例如 intbooleanfloat)使用 instanceof 运算符,因为它们只能包含 numbers/values 他们的名字已经告诉你了(整数代表 inttruefalse 代表 boolean,浮点数代表 float)。

类型为 classes 的变量,但是 可以 instanceof 一起使用,因为 classes 可以(通常)扩展.变量 Foo variable 也可能包含 class Bar 的实例(例如,如果 Bar extends Foo),因此您实际上可能需要此处的 instanceof 运算符。