HOWTO · Java

Java Not InstanceOf

本教程演示如何在 Java 中否定 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