简体   繁体   English

几乎每个方法调用上的声纳“可能的空指针取消引用”错误

[英]Sonar 'Possible null pointer dereference' error on almost every method call

I am fetching some data from a remote service using Spring's RestTemplate:我正在使用 Spring 的 RestTemplate 从远程服务获取一些数据:

ResponseEntity<....> result = restTemplate.exchange(....);

...and then I am using result for further processing, and hence I am invoking various methods on it, like: ...然后我使用结果进行进一步处理,因此我在其上调用了各种方法,例如:

result.getHeaders().getContentType().getType()
result.getBody()
result.getHeaders().getContentType().getSubtype()

Sonar doesn't like this code and reports 'Possible null pointer dereference' error on almost all of these method calls. Sonar 不喜欢这段代码,并在几乎所有这些方法调用中报告“可能的空指针取消引用”错误。 It seems I need to have null check on almost every return value.似乎我需要对几乎每个返回值进行空检查。

This makes my code with too many null checks.这使我的代码有太多的空检查。

Can this be avoided?这可以避免吗?

Use Optional from java 8 JavaDocs :使用 java 8 JavaDocs 中的Optional

String contentType = Optional.ofNullable(result)
  .map(HttpResponse::getHeaders)
  .map(Headers::getContentType)
  .map(ContentType::getType)
  .orElse(null);

HttpResponse should be the type of result , Headers should be the return type of getHeaders() and so on. HttpResponse应该是result的类型, Headers应该是getHeaders()的返回类型等等。

You can use other terminating operators other than orElse() :您可以使用orElse()以外的其他终止运算符:

.orElseGet(() -> someOtherProcess());
.orElseThrow(() -> new RuntimeException("Content Type was Null"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SONAR中可能的空指针取消引用 - Possible null pointer dereference in SONAR 声纳:由于被调用方法的返回值,可能取消引用空指针 - Sonar : Possible null pointer dereference due to return value of called method 声纳:由于被调用方法的返回值,可能的 null 指针取消引用 - Sonar: Possible null pointer dereference due to return value of called method 如何在声纳中解决此“可能的 null 指针取消引用”关键问题? - How to fix this "possible null pointer dereference" critical issue in Sonar? 空指针取消引用问题从未在声纳中引发 - Null Pointer dereference issue never thrown in sonar 由于调用方法的返回值,Sonar 可能出现问题 null 指针取消引用。 方法的返回值在没有 null 检查的情况下被取消引用 - Sonar Issue-Possible null pointer dereference due to return value of called method. Return value from a method is dereferenced without a null check FindBugs:可能的空指针取消引用 - FindBugs: Possible null pointer dereference 由于被调用方法的返回值,可能在 […] 中取消引用 null 指针 - Possible null pointer dereference in […] due to return value of called method Java + Eclipse:错误的可能的空指针取消引用? - Java + Eclipse: False possible null pointer dereference? SonarQube显示可能的空指针取消引用 - SonarQube shows Possible null pointer dereference
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM