声纳严重违规 - 以前取消引用的Nullcheck值

ric*_*mes 5 java

对于我在我的一个测试类中的下面一段代码,Sonar抛出了一个严重的违规行为 - 正确性 - 以前取消引用的Nullcheck值

 if (testLst != null && !testLst.isEmpty()) {
        for (Test test : testLst) {
            if (test.getName().equalsIgnoreCase("TEST")) {
            // do blah
            }
Run Code Online (Sandbox Code Playgroud)

有人可以对此我做错了吗?

编辑:这里的答案之一建议这是因为我之前可以访问变量,因此空检查是多余的.但事实并非如此.这是我的null检查之前的代码行.

 testLst = myTest.getValues(); //I am basically populating the array by doing a get, but I am not accessing the list itself by doing a get on it directly - like testLst.get()
 if (testLst != null && !testLst.isEmpty()) {
            for (Test test : testLst) {
                if (test.getName().equalsIgnoreCase("TEST")) {
                // do blah
                }
Run Code Online (Sandbox Code Playgroud)

man*_*uti 14

当您检查变量的值是否为空时(在这种情况下testLst),而您之前已经访问过该变量,则会显示此消息.不需要空检查,因为如果值为null,NullPointerException则会抛出一个.

例:

testLst.remove(something);
if (testLst != null && !testLst.isEmpty()) {
    for (Test test : testLst) {
       if (test.getName().equalsIgnoreCase("TEST")) {
        // do blah
        }
Run Code Online (Sandbox Code Playgroud)

检查testLst != null是多余的,因为在程序到达if语句时,testLst不能为null,否则先前的语句testLst.remove(something)会抛出一个NullPointerException.在这种情况下,您应该在访问之前将null检查testLst放在可以为null的位置:

if(testLst != null) {
   testLst.remove(something);
   if (!testLst.isEmpty()) {
       for (Test test : testLst) {
          if (test.getName().equalsIgnoreCase("TEST")) {
           // do blah
          }
Run Code Online (Sandbox Code Playgroud)