Inspectopedia Help

'instanceof' check for 'this'

Reports usages of instanceof or getClass() == SomeClass.class in which a this expression is checked.

Such expressions indicate a failure of the object-oriented design, and should be replaced by polymorphic constructions.

Example:

class Super { void process() { if (this instanceof Sub) { // warning doSomething(); } else { doSomethingElse(); } } } class Sub extends Super {}

To fix the problem, use an overriding method:

class Super { void process() { doSomethingElse(); } } class Sub extends Super { @Override void process() { doSomething(); } }

Inspection Details

Available in:

IntelliJ IDEA 2023.3, Qodana for JVM 2023.3

Plugin:

Java, 233.SNAPSHOT

Last modified: 13 July 2023