在while循环条件下为布尔基元获取无法访问的代码,但不能为布尔包装器获取代码

题:

  • flag1, flag3& flag5AFAIK 在编译时本身解析变量值,因此它必须给出错误。

  • flag2, flag4& Boolean.FALSE: 为什么我们没有得到编译时错误

  • 找到 1 个参考,但不完全相同。

    为什么在显式布尔测试上有死代码警告,而在隐式测试上没有

代码:

public static void main(final String[] args) {
    final boolean flag1 = false;

    final Boolean flag2 = Boolean.parseBoolean("false");

    final boolean flag3 = !true;

    final Boolean flag4 = 100 == 20;

    final boolean flag5 = 10 >= 20;

    while (flag1) { System.out.println("this is unreachable code with compile error"); break;  }

    while (flag5) { System.out.println("this is unreachable code with compile error"); break;  }        

    while (flag3) { System.out.println("this is unreachable code with compile error"); break;  }
    
    while (flag2) { System.out.println("this is uncreachable code without compile error"); break;  }

    while (flag4) { System.out.println("this is uncreachable code without compile error"); break;  }

    while (Boolean.FALSE) { System.out.println("this is uncreachable code without compile error"); break;  }

}

输出:

.comlogicst4_19_Tst.java:15: error: unreachable statement
        while (flag1) { System.out.println("this is unreachable code with compile error"); break;  }
                      ^
.comlogicst4_19_Tst.java:17: error: unreachable statement
        while (flag5) { System.out.println("this is unreachable code with compile error"); break;  }        
                      ^
.comlogicst4_19_Tst.java:19: error: unreachable statement
        while (flag3) { System.out.println("this is unreachable code with compile error"); break;  }        
                      ^
3 errors
java version "1.8.0_261"
Java(TM) SE Runtime Environment (build 1.8.0_261-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.261-b12, mixed mode)

回答

该可达性规则有许多,他们指的地方常量表达式与值truefalse

在您的代码中flag1flag3flag5都是常量表达式,因此它们的值用于可达性规则。

flag2flag4并且Boolean.FALSE恒定的表达式,并且不能是,因为常量表达式规则开始:

常量表达式是表示原始类型值或不会突然完成并且仅使用以下内容组成的字符串的表达式: [...]

Boolean既不是原始类型也不是String,因此类型的表达式Boolean永远不会被归类为常量表达式。(该规则可以很容易地被写入例如,它可能是,但这不是事情是这样的。)


以上是在while循环条件下为布尔基元获取无法访问的代码,但不能为布尔包装器获取代码的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>