java如果某些东西总是错误的,它会被编译吗?
我经常使用布尔值来控制调试的输出:
void fooBar() {
boolean debug = false;
if (debug) System.out.println("will this be in the compile if debug is false?");
// code for the method
}
我想知道,这个布尔值是否在方法中声明为false。那么它是否会被编译?(因为它是多余的)
如果我的解释不清楚,将按上述方式或类似方式编制:
void fooBar() {
// code for the method
}
# 1 楼答案
如果控制变量为
static final
可以看出,没有为
println
生成任何内容对于不相信的人来说,将
debug
设置为true
也是一样的:我的理解是,即使
static final
变量在另一个类中,这也是正确的,但我从未尝试过这一特性记录在"unreachable statements"的JLS部分,该部分底部附近,以及"binary compatibility for final fields and constants"部分
# 2 楼答案
是的,它将被编译,其字节码将被发送到类文件中(至少由Oracle的编译器)。这很容易检查:
。。。看看结果
如果您使用Oracle的HotSpot运行它,并且如果它是代码中的HotSpot,如果它得到了JIT,我不会感到惊讶
然而,在HotLickspoints out中添加
final
:。。。允许编译器不发出字节码。代码仍必须编译