Reputation: 186
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?
Upvotes: 4
Views: 7486
Reputation: 21576
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.
Upvotes: 9