问题描述
我有一个方法,其中参数用 @Nonnull
注释标记。调用该方法的代码必须检查该值是否为null。它不是直接 x!= null
检查,而是在另一个类上调用实用程序方法。 (在实际代码中,实用程序方法还检查它是否为空字符串。)
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).
我的问题是Intellij Idea在Nonnull方法调用上显示检查警告,说我的变量可能为空。我知道它不能为null因为实用方法检查 - 我怎么能告诉检查员呢?
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);
}
}
这使用JSR 305注释。
This uses the JSR 305 annotations.
在这个例子中,在第一次中调用 useObject
Intellij在<$ c上发出警告$ c> x 参数说Argument'x'可能为null。在第二次调用中,没有警告。
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.
推荐答案
我不相信有任何办法使用按原样编写的代码来解决警告。我希望发现IntelliJ支持 @SuppressWarnings
的值,你可以在 useObject(x)
语句中使用它,但根据,它没有。您可能只需咬紧牙关并将代码更改为以下内容:
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 @SuppressWarnings
that you could use on the useObject(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:
if (x != null && !isBlank(x)) {
useObject(x);
}
请注意,我重命名了方法 isNull
到 isBlank
因为我的理解是你正在调用的实际方法检查 null
也检查其他条件。
Notice that I renamed the method isNull
to isBlank
since it is my understanding that the actual method you're calling that does the check for null
checks other conditions as well.
这篇关于如何使IntelliJ IDEA了解我的空检查方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!