Java 声纳问题-参数必须为非Null,但标记为可为Null
我写了这个谓词,sonar对此表示不满。我不知道如何纠正这一违规行为。请帮助:Java 声纳问题-参数必须为非Null,但标记为可为Null,java,collections,guava,sonarqube,Java,Collections,Guava,Sonarqube,我写了这个谓词,sonar对此表示不满。我不知道如何纠正这一违规行为。请帮助: import com.google.common.base.Predicate; import java.util.Map; public final class FooPredicate { private FooPredicate(){} public static Predicate<Map.Entry<Long,Long>> isFirstElement(fina
import com.google.common.base.Predicate;
import java.util.Map;
public final class FooPredicate {
private FooPredicate(){}
public static Predicate<Map.Entry<Long,Long>> isFirstElement(final Long o) {
return new Predicate<Map.Entry<Long,Long>>() {
@Override
public boolean apply(Map.Entry<Long,Long> foo) {
return foo.getKey().equals(o);
}
};
}
}
apply方法被定义为接受一个null值,对此我无能为力。声纳和番石榴不是在这里战斗吗
> boolean apply(@Nullable
> T input)
>
> Returns the result of applying this predicate to input. This method is
> generally expected, but not absolutely required, to have the following
> properties:
>
> Its execution does not cause any observable side effects.
> The computation is consistent with equals; that is, Objects.equal(a, b) implies that predicate.apply(a) ==
> predicate.apply(b)).
>
> Throws:
> NullPointerException - if input is null and this predicate does not accept null arguments
您正在执行
foo.getKey()
。如果foo
为null,则将引发NullPointerException,但您没有声明foo
不得为null
使用前请先检查空值foo
if (foo != null) {
return foo.getKey().equals(o);
} else {
return null;
}
是的,不同的工具对@Nullable有不同的解释,无论Guava做什么,都会有一些工具抱怨它。Guava问题指的是同样的事情:
if (foo != null) {
return foo.getKey().equals(o);
} else {
return null;
}