Java


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

Summary

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.

Properties

Class Name Instanceof Always True (Java)
Significance reliability
Mnemonic JAVA.CLASS.IOF.T
Categories
CWE CWE:571 Expression is Always True
Availability Available for Java only.
Enabling Checks for this warning class are enabled by default. To disable them, add the following WARNING_FILTER rule to the project configuration file.
WARNING_FILTER += discard class="Instanceof Always True (Java)"

Example

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).

Resolution

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

Relevant Configuration File Parameters

The following configuration file parameters affect checks for this warning class.