【问题标题】:Sonar issue - parameter must be nonnull but is marked as nullable声纳问题 - 参数必须为非空,但被标记为可为空
【发布时间】:2014-11-30 10:41:07
【问题描述】:

我已经写了这个谓词,而声纳正在抱怨它。我不确定如何解决此违规问题。请帮忙:

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 方法被定义为可以为空,我对此无能为力。 Sonar 和 Guava 不是在打架吗?

> 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

【问题讨论】:

  • 是的,不同的工具对@Nullable有不同的解释,不管Guava做什么,都会有一些工具抱怨。

标签: java collections guava sonarqube


【解决方案1】:

你正在做foo.getKey()。如果foo 为null,则会抛出NullPointerException,但您并未声明foo 不能为null。

在使用之前检查 foo 是否为空。

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-26
  • 2018-06-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-20
  • 2012-01-08
相关资源
最近更新 更多