Reputation: 31
I'm having difficulty with Findbugs complaining about springs HttpEntity.getBody()
.
Below you'll see I call response.getBody().length
, which I understand could cause a NPE. However when I wrap it in if (response.getBody() != null)
, it still complains. It only does this in Spring 2.0 (not 1.5) which appears to be related to the @Nullable
annotation added to the method.
Can I get an explanation why even when I wrap it in a null check, it still complains when I get the length of it?
Bug type NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE
ResponseEntity<SomeClass[]> response = restTemplate.exchange(someUrl, HttpMethod.GET, httpEntity,
SomeClass[].class);
for (int i = 0; response.getBody().length > i; i++) {
doSomething()
}
Upvotes: 3
Views: 935
Reputation: 141
According to Spot bugs documentation the reason for this occuring is :
'The return value from a method is dereferenced without a null check, and the return value of that method is one that should generally be checked for null. This may lead to a NullPointerException when the code is executed.'
fixed it by:
Optional <T> body = Optional.ofNullable(response.getBody);
if (body.isPresent()) {
//use body
}
You are getting the warning because getBody method has been annotated as Nullable and spotBugs / findbugz expects that an explicit null checker be made before using the value. Works well for me.
Upvotes: 1