[英]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.