Home > Back-end >  IntelliJ Java inspection non primitive Boolean in 'if' statements
IntelliJ Java inspection non primitive Boolean in 'if' statements

Time:09-18

I would like to be warned in my Java code where an 'if' statement is based on a non-primitive Boolean condition.

For example:

void anyMethod() {
   if(getCondition()) {
   ...
   }
}

Boolean getCondition() {
...
}

where getCondition() may return TRUE, FALSE or null

That kind of 'if' control may produce NullPointerException and should be avoided.

In IntelliJ, I tried to create a custom inspection pattern but mine doesn't work. If I explicitely put a @Nullable annotation on getCondition() then the default inspections work, but this solution still relies on a manual task that may not be done rigorously (putting @Nullable everywhere a method return a Boolean) and does not cover codes where the condition is a local Boolean variable.

How can I write an IntelliJ inspection pattern to track this case?

Thanks a lot.

CodePudding user response:

You can create a custom inspection for this like so:

First go to the inspections tab in the IntelliJ settings page. Then click on the plus button and then "Add Search Template"

enter image description here

Then use the pattern:

if ($expression$) {$statement$;}

Add the filter "type=java.lang.Boolean" to the $expression$ template and "count=[0,inf]" to the $statement$ template. Remember to put the cursor over the template when adding filters.

The end result should look like this:

enter image description here

Give the inspection a name, a tooltip, a description, and a suppress ID, and you're done.

  • Related