Java Not InstanceOf

Sheeraz Gul 2023年10月12日
Java Not InstanceOf

InstanceOf 关键字检查引用变量是否包含给定的对象引用类型。它返回布尔类型,所以我们也可以否定它们。

本教程演示如何在 Java 中否定 InstanceOf 或使用 Not InstanceOf

在 Java 中使用 Not InstanceOf

instanceof 返回一个布尔值,因此否定它将返回 false 值。取反 InstanceOf 与 Java 中的其他取反类似。

例如:

if (!(str instanceof String)) { /* ... */
}

或者:

if (str instanceof String == false) { /* ... */
}

让我们尝试一个完整的 Java 示例来展示 Not InstanceOf 在 Java 中的用法。

package delftstack;

class Delftstack_One {}

class Delftstack_Two extends Delftstack_One {}

public class Negate_InstanceOf {
  public static void main(String[] args) {
    Delftstack_Two Demo = new Delftstack_Two();

    // A simple not instanceof using !
    if (!(Demo instanceof Delftstack_Two)) {
      System.out.println("Demo is Not the instance of Delftstack_Two");
    } else {
      System.out.println("Demo is the instance of Delftstack_Two");
    }

    // not instanceof using !
    if (!(Demo instanceof Delftstack_One)) {
      System.out.println("Demo is Not the instance of Delftstack_One");
    } else {
      System.out.println("Demo is the instance of Delftstack_One");
    }

    // instanceof returns true for all ancestors, and the object is the ancestor of all classes in
    // Java

    // not instance using == false
    if ((Demo instanceof Object) == false) {
      System.out.println("Demo is Not the instance of Object");
    } else {
      System.out.println("Demo is the instance of Object");
    }

    System.out.println(Demo instanceof Delftstack_One);
    System.out.println(Demo instanceof Delftstack_Two);
    System.out.println(Demo instanceof Object);
  }
}

上面的代码创建了两个父子类来展示 Not InstanceOf 的用法。我们使用了上述两种方法。

见输出:

Demo is the instance of Delftstack_Two
Demo is Not the instance of Delftstack_One
Demo is the instance of Object
false
true
true
作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook