如何在外部库中使用findbugs @Nonnull? [英] How to use findbugs @Nonnull with external libraries?

查看:108
本文介绍了如何在外部库中使用findbugs @Nonnull?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始在现有项目上使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆