Java


JAVA.CLASS.IOF.T : Instanceof Always True (Java)

要旨

An instanceof test is always true.

This checker looks for instanceof operators that are useless, in the sense that they are always true or always false and can hence be removed from the code. This can improve the efficiency of the program. Moreover, a useless instanceof test is often the sign of a programming bug.

プロパティ

クラス名 Instanceof Always True (Java)
日本語クラス名 Instanceof Always True (Java)
クラス分類 信頼性 (reliability)
ニーモニック JAVA.CLASS.IOF.T
カテゴリー
CWE CWE:571 Expression is Always True
対応言語 Java で利用可能です。
有効/無効設定 このワーニングクラスのチェックはデフォルトで有効になっています。チェックを無効にするにはプロジェクト設定ファイル (configuration file)に以下の WARNING_FILTER ルールを追加してください。
WARNING_FILTER += discard class="Instanceof Always True (Java)"

public class Main {
  public static void main(String[] args) {
      A a = new B();
      switch ((int) (System.currentTimeMillis() % 3)) {
          case 0: case 1:
              a = new A(); break;
          case 2:
              a = new C(); break;
      }
      if (a instanceof C)
          foo(a);
  }

  private static void foo(A par) {
      if (par instanceof B)   // "Instanceof Always True (Java)" warning issued here
          System.out.println("par is a B");
  }
}

public class A {}
public class B extends A {}
public class C extends B {}

In this case, the programmer should probably consider defining method foo() as foo(B par).

解決法

Check if the instanceof operator can be actually removed and that it is not the sign of an actual programming bug.

関連のある設定ファイルパラメータ

設定ファイルの以下のパラメータがこのワーニングクラスのチェックに影響します。