如何在外部库中使用findbugs @Nonnull? [英] How to use findbugs @Nonnull with external libraries?
问题描述
我开始在现有项目上使用findbugs @Nonnull
和@CheckForNull
批注,以防止出现NPE,并认为它的效果很好.
我使用@Nonnull
作为返回类型和参数的默认值,仅通过添加默认值就已经发现了一些NPE.现在,我发现了一种与此类似的方法:
I started using findbugs @Nonnull
and @CheckForNull
annotations on an existing Project, to prevent NPEs, and think it works quite nice.
I use @Nonnull
as default for return types and parameters and found already a few NPEs, just by adding the default values. Now I found a method similar to this:
@Nonnull
private Integer getInteger(String key) {
return Map.get(key);
}
它不会产生警告.我知道为什么会这样,但是我该如何解决呢?您如何在项目中解决此问题?
And it does not produce a warning. I understand why this is the case, but how can I get around this? How do you work around this in your projects?
首选可全局应用的解决方案,例如类似于@ApplyCheckForNullToAllExternalCalls
.
A solution that can be globally applied would be preferred, e.g. something like @ApplyCheckForNullToAllExternalCalls
.
推荐答案
通过将注释添加到包的package-info.java
文件中,您可以将@CheckForNull
应用于包中的所有方法返回值(和/或参数),但是您将无法控制单个方法.
You can apply @CheckForNull
to all method return values (and/or parameters) within a package by adding the annotation to the package's package-info.java
file, but you won't have control over individual methods.
首先,在项目的实用程序包中创建@ReturnValuesAreCheckForNullByDefault
.
First, create @ReturnValuesAreCheckForNullByDefault
in a utility package of your project.
@Documented
@CheckForNull
@TypeQualifierDefault(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ReturnValuesAreCheckForNullByDefault { /* noop */ }
下一步,创建src/java/util/package-info.java
.
@ReturnValuesAreCheckForNullByDefault
package java.util;
import my.project.util.ReturnValuesAreCheckForNullByDefault;
最后,享受您的FindBugs警告.
Finally, enjoy your FindBugs warnings.
@Nonnull
public String getValue() {
Map<String, String> values = new HashMap<>();
return values.get("foo"); // <-- Possible null pointer dereference ...
}
这样做的问题是java.*
程序包中有许多方法以合同方式不返回null
.在不检查null
的情况下使用它们会发出警告.例如,此NPE安全代码也会引发警告:
The problem with doing this is that there are many methods in the java.*
packages that contractually do not return null
. Using these without checking for null
will raise warnings. For example, this NPE-safe code also raises a warning:
@Nonnull
public Set<String> getNotNull() {
Map<String, String> values = new HashMap<>();
return values.keySet();
}
您可以使用@SuppressFBWarnings
禁止显示警告,但这可能会使您的代码显得过于混乱.
You can suppress the warning with @SuppressFBWarnings
, but this may clutter up the code too much for your liking.
这篇关于如何在外部库中使用findbugs @Nonnull?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!