Google Guava Function界面中的@Nullable输入会触发FindBugs警告

vit*_*aly 35 java findbugs guava

将com.google.common.base.Function(从接口谷歌番石榴)定义apply为:

@Nullable T apply(@Nullable F input);

该方法具有以下javadoc注释:

@throws NullPointerException if {@code input} is null and this function does not accept null arguments.

FindBugs抱怨我的Function实现:

private static final class Example implements Function<MyBean, String> {
    @Override
    @Nullable
    public String apply(@Nullable MyBean input) {
        if (null == input) {
            throw new NullPointerException();
        }
        return input.field;
    }
}
Run Code Online (Sandbox Code Playgroud)

具有高优先级警告:

NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE,优先级:高

输入必须是非空的,但标记为可为空

此参数始终以要求它为非空的方式使用,但该参数明确注释为Nullable.使用参数或注释是错误的.

我的函数不支持null输入,如果是这种情况则抛出异常.如果我理解正确,FindBugs会将此视为非null的要求.

对我来说,它看起来像一个矛盾:输入是@Nullable但是当它为null时,方法@throws NullPointerException.我错过了什么吗?

摆脱我能看到的警告的唯一方法是手动抑制.(显然,番石榴代码不受我的控制).

关于@Nullable注释,FindBugs,Guava或我自己的用法有什么问题?

Xae*_*ess 28

你的实现是错误的;)

基本上文档说(我会解释和强调):

@throws NullPointerExceptionif input为null且具体函数实现不接受空参数

通过实现您的功能,您必须确定它是否接受空值.在第一种情况下:

private static final class Example implements Function<MyBean, String> {
    @Override
    @Nullable
    public String apply(@Nullable MyBean input) {
        return input == null ? null : input.field;
    }
}
Run Code Online (Sandbox Code Playgroud)

在第二种情况:

private static final class Example implements Function<MyBean, String> {
    @Override
    @Nullable
    public String apply(MyBean input) {
        if (null == input) {
            throw new NullPointerException();
        }
        return input.field;
    }
}
Run Code Online (Sandbox Code Playgroud)

在两个示例中,都允许返回null.

编辑:

请注意,Guava @javax.annotation.ParametersAreNonnullByDefault在所有包上使用,因此如果@Nullable存在则意味着"暂停全局@Nonnull并在此处允许空值",如果不存在则意味着"此处禁止空值".

也就是说,您可能希望@Nonnull在您的参数或@ParametersAreNonnullByDefault包中使用注释来告诉FindBugs Function的参数不能为null.

编辑2:

事实证明这个案例是众所周知的问题,请参阅评论#3(来自Guava的主要负责人Kevin Bourrillion,关于他与Bill Pugh的对话,Findbugs的领导):

我的参考是与比尔·普格的一系列面对面交谈.他毫不含糊地断言,这@Nullable意味着只有某些子类型 可能接受null.这似乎是由findbugs为我们证实的 - 我们的代码非常干净地通过了可空性检查(尽管我们应该再次检查,因为这个特定的功能更改已经完成).

  • 注释已经由框架接口指定,我不能(也不打算)从那里删除.我可以编辑的唯一代码是我自己的代码(=实现).我从我的实现中删除了@Nullable注释,但FindBugs一直在抱怨. (4认同)
  • @vitaly似乎是[已知问题](http://code.google.com/p/guava-libraries/issues/detail?id=920),可能取决于您使用的FindBugs版本. (3认同)
  • 用`@ javax.annotation.Nonnull`标记 - 但它没有帮助,仍然得到`这个参数总是以一种要求它是非空的方式使用,但是参数被明确地注释为Nullable. (2认同)