Java 运算符

Java instanceof 运算符检查对象是否是特定类型(类、子类或接口)的实例。如果对象是特定类型的实例,则返回 true,否则返回 false。

语法

objectName instanceof objectType

返回值

如果object 是特定类型(类、子类或接口)的实例,否则为 false。

示例:

下面的示例显示了 instanceof 的用法

public class MyClass {
  public static void main(String[] args) {
    String str = "Hello World";
    MyClass obj = new MyClass();

    //使用instanceof运算符
    boolean x = str instanceof String;
    System.out.println("str instanceof String: " + x); 

    //使用instanceof运算符
    boolean y = obj instanceof MyClass;
    System.out.println("obj instanceof MyClass: " + y); 
  }
}

上述代码的输出将是:

str instanceof String: true
obj instanceof MyClass: true

继承期间的Java instanceof

instanceof运算符可以是用于检查子类类型的对象是否也是父类的实例。考虑下面的示例:

class Shape{}
class Circle extends Shape {}

public class MyClass {
  public static void main(String[] args) {
    Shape sobj = new Shape();
    Circle cobj = new Circle();

    //使用instanceof运算符
    if(sobj instanceof Shape) 
      System.out.println("sobj is an instance of Shape.");
    else
      System.out.println("sobj is NOT an instance of Shape."); 

    if(sobj instanceof Circle) 
      System.out.println("sobj is an instance of Circle.");
    else
      System.out.println("sobj is NOT an instance of Circle."); 

    if(cobj instanceof Shape) 
      System.out.println("cobj is an instance of Shape.");
    else
      System.out.println("cobj is NOT an instance of Shape."); 

    if(cobj instanceof Circle) 
      System.out.println("cobj is an instance of Circle.");
    else
      System.out.println("cobj is NOT an instance of Circle.");       
  }
}

上述代码的输出将是:

sobj is an instance of Shape.
sobj is NOT an instance of Circle.
cobj is an instance of Shape.
cobj is an instance of Circle.

接口中的 Java instanceof

The instanceof运算符可用于检查类类型的对象是否也是该类实现的接口的实例。考虑下面的示例:

interface Shape{}
class Circle implements Shape {}

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

    Circle cobj = new Circle();

    //使用instanceof运算符
    if(cobj instanceof Shape) 
      System.out.println("cobj is an instance of Shape.");
    else
      System.out.println("cobj is NOT an instance of Shape."); 

    if(cobj instanceof Circle) 
      System.out.println("cobj is an instance of Circle.");
    else
      System.out.println("cobj is NOT an instance of Circle.");       
  }
}

上述代码的输出将是:

cobj is an instance of Shape.
cobj is an instance of Circle.