声纳:几乎每个方法调用都出现了“可能的空指针解引用”错误。

huangapple go评论75阅读模式
英文:

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

问题

我正在使用Spring的RestTemplate从远程服务获取一些数据:

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

然后我在进一步处理时使用了result,因此我在它上面调用了各种方法,比如:

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

Sonar不喜欢这段代码,并且在几乎所有这些方法调用上报告了'可能的空指针解引用'错误。看起来我需要在几乎每个返回值上都进行空值检查。

这使得我的代码中充斥着太多的空值检查。

这个情况能避免吗?

英文:

I am fetching some data from a remote service using Spring's 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. 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?

答案1

得分: 1

使用Java 8中的Optional JavaDocs

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

HttpResponse 应该是 result 的类型,Headers 应该是 getHeaders() 的返回类型,以此类推。

除了 orElse(),您还可以使用其他终止操作符:

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

Use Optional from java 8 JavaDocs:

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.

You can use other terminating operators other than orElse():

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

huangapple
  • 本文由 发表于 2020年9月26日 02:50:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64069864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定