I have a method where a parameter is marked with the @Nonnull annotation. The code which calls the method has to check whether the value is null. Rather than just a straight x != null check, it is calling a utility method on another class. (In the real code, the utility method also checks whether it is a blank String).
My problem is that Intellij Idea is showing an inspection warning on the Nonnull method call, saying that my variable “might be null”. I know it cannot be null because of the utility method check – how can I tell the inspector that?
Since that is a bit abstract, here’s a minimal example of what I mean:
package org.ethelred.ideatest;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
/**
* tests annotations
*/
public class AnnotationChecker
{
public static void main(String[] args)
{
String x = null;
if(args.length > 0)
{
x = args[0];
}
if(!isNull(x))
{
useObject(x);
}
if(x != null)
{
useObject(x);
}
}
public static boolean isNull(@CheckForNull Object o)
{
return o == null;
}
public static void useObject(@Nonnull Object o)
{
System.out.println(o);
}
}
This uses the JSR 305 annotations.
In this example, in the first call to useObject Intellij puts a warning on the x parameter saying “Argument ‘x’ might be null”. In the second call, there is no warning.
I don’t believe there’s any way to resolve the warning with the code written as it is. I was hoping to find that IntelliJ supports a value for
@SuppressWarningsthat you could use on theuseObject(x)statement, but according to this source it does not. You may just have to bite the bullet and change your code to something like the following:Notice that I renamed the method
isNulltoisBlanksince it is my understanding that the actual method you’re calling that does the check fornullchecks other conditions as well.