英文:
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"));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论