Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring 2.0 findbugs nullable throws error even when wrapped in null check

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()
                    }
like image 454
Ronnie J Avatar asked Dec 06 '25 04:12

Ronnie J


1 Answers

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.

like image 155
Ugo Uchegbu Avatar answered Dec 08 '25 21:12

Ugo Uchegbu