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"
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:
Give the inspection a name, a tooltip, a description, and a suppress ID, and you're done.