我如何修复squid:S2259`NullPointerException可能被抛出为' getString'可以在这里筑巢吗?

时间:2016-10-28 15:59:26

标签: java sonarqube

我有以下代码块

/**
 * Checks if the server name is equal to localhost in the servlet request.
 *
 * @param request
 *            servlet request
 * @return true if the server name is equal to localhost.
 */
public boolean isLocalHost(@Nonnull final ServletRequest request) {

    return settings != null && settings.getString(LOCALHOST) != null && settings.getString(LOCALHOST).equals(request.getServerName());
}

但Sonarqube继续抱怨getString可能是可以为空的,即使从我所知道的可能由于布尔短路而无法发生

1 个答案:

答案 0 :(得分:3)

SonarQube无法识别settings.getString的连续调用将返回相同的值。

可能是正确的,因为如果其他线程可以在调用之间修改设置。

因此,在评论中提到的@Andreas为变量赋值应解决此问题。

<强> UPD

 public boolean isLocalHost(@Nonnull final ServletRequest request) {
     if(settings == null) {
         return false;
     }

     String localhost = settings.getString(LOCALHOST);

     return localhost != null && localhost.equals(request.getServerName());
 }

或从另一方检查变量:

 public boolean isLocalHost(@Nonnull final ServletRequest request) {
    String requestServerName = request.getServerName();

    return settings != null && requestServerName != null && requestServerName.equals(settings.getString(LOCALHOST));
 }

UPD2 :删除了其中一个代码段,因为HttpServletRequest.getServerName() occasionally returning null in concurrent use?