Possible null pointer dereference error in this code:
if(!Util.isNull(dir)){
if (dir.isDirectory()){
if(!Util.isNull(dir.list()))
if((!Util.isNull(dir.list().length))) // issue reported here
if(dir.list().length == 0) // another issue reported here
if (dir.delete())
LOGGER.info("deleted:");
}
}
How can I fix these issues?
You check, that dir.list()
is not null. Afterwards you do other calls to dir.list()
, and assume, that is cannot be null in this case.
SonarJava tries to tell you, that even though dir.list()
has not been null in the first place, it could have turned null for the second/third call.
To solve this issue:
dir.list()
in a variableThis is also know as the extract variable refactoring, and it has additional good effects. If you don't expect the result of dir.list()
to change between calls, then you will improve the performance as well, since the program doesn't need to access the filesystem again to produce the content of the directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With