How to use findbugs @Nonnull with external libraries?

我的梦境 提交于 2019-12-24 04:02:15

问题


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?

A solution that can be globally applied would be preferred, e.g. something like @ApplyCheckForNullToAllExternalCalls.


回答1:


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.

First, create @ReturnValuesAreCheckForNullByDefault in a utility package of your project.

@Documented
@CheckForNull
@TypeQualifierDefault(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ReturnValuesAreCheckForNullByDefault { /* noop */ }

Next, create src/java/util/package-info.java.

@ReturnValuesAreCheckForNullByDefault
package java.util;

import my.project.util.ReturnValuesAreCheckForNullByDefault;

Finally, enjoy your FindBugs warnings.

@Nonnull
public String getValue() {
    Map<String, String> values = new HashMap<>();
    return values.get("foo");    // <-- Possible null pointer dereference ...
}

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();
}

You can suppress the warning with @SuppressFBWarnings, but this may clutter up the code too much for your liking.



来源:https://stackoverflow.com/questions/14194304/how-to-use-findbugs-nonnull-with-external-libraries

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!