声纳问题 - 参数必须是非空的,但标记为可为空

时间:2014-11-30 10:41:07

标签: java collections guava sonarqube

我写了这个谓词,声纳正在抱怨它。我不知道如何修复此违规行为。请帮忙:

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方法的Foo参数。

Dodgy - Parameter must be nonnull but is marked as nullable
foo must be nonnull but is marked as nullable

apply方法被定义为可以为空,我对此无能为力。声纳和番石榴在这里战斗不是吗?

> 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

1 个答案:

答案 0 :(得分:4)

你在做foo.getKey()。如果foo为null将抛出NullPointerException,但您没有声明foo不能为空。

使用前请先检查foo

if (foo != null) {
   return foo.getKey().equals(o);
} else {
   return null;
}