gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:54:05 24 4
gpt4 key购买 nike

com.google.common.base.Function 接口(interface)(来自 Google Guava)将 apply 定义为:

@Nullable T 应用(@Nullable F 输入);

该方法有以下javadoc注释:

@throws NullPointerException 如果 {@code input} 为 null 并且此函数不接受 null 参数

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

带有高优先级警告:

NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE, Priority: High

input must be nonnull but is marked as nullable

This parameter is always used in a way that requires it to be nonnull, but the parameter is explicitly annotated as being Nullable. Either the use of the parameter or the annotation is wrong.

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

对我来说,这看起来很矛盾:输入是@Nullable,但是当它为空时方法@throws NullPointerException。我错过了什么吗?

我可以看到摆脱警告的唯一方法是手动抑制。 (显然, Guava 代码不在我的控制范围内)。

@Nullable 注解、FindBugs、Guava 还是我自己的用法谁错了?

最佳答案

你的实现是错误的;)

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

@throws NullPointerException if input is null and the concrete function implementation does not accept null arguments

通过实现你的函数,你必须决定它是否接受空值。第一种情况:

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

第二种情况:

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

在这两个示例中都允许返回 null。

编辑:

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

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

编辑 2:

结果是 this case is known issue ,请参阅评论 #3(来自 Guava 的首席开发人员 Kevin Bourrillion,关于他与 Findbugs 的负责人 Bill Pugh 的对话):

My reference was a series of in-person conversations with Bill Pugh. He asserted unambiguously that @Nullable means only that some subtypes might accept null. And this seems to be borne out by findbugs for us -- our code passes the nullability checks pretty cleanly (though we should check again since this particular Function change was made).

关于java - Google Guava Function 界面中的@Nullable 输入触发 FindBugs 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12422473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com