简体   繁体   English

SonarQube显示可能的空指针取消引用

[英]SonarQube shows Possible null pointer dereference

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. 您检查dir.list()是否不为null。 Afterwards you do other calls to dir.list() , and assume, that is cannot be null in this case. 然后,您对dir.list()进行其他调用,并假定在这种情况下不能为null。

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. SonarJava试图告诉您,即使dir.list()最初没有为null,第二次/第三次调用也可能为null。

To solve this issue: 要解决此问题:

  1. save the result of dir.list() in a variable dir.list()的结果保存在变量中
  2. check that the variable is not null 检查变量不为空
  3. use the variable 使用变量

This 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. 如果您不希望dir.list()的结果在dir.list()调用之间发生变化,那么您还将提高性能,因为该程序无需再次访问文件系统即可产生目录的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM