有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

}

共 (2) 个答案

  1. # 1 楼答案

    如果控制变量为static final

    public class CondComp {
        static final boolean debug = false;
        public void doIt() {
            if (debug) System.out.println("Here we are");
        }
    }
    
    Compiled from "CondComp.java"
    public class CondComp {
      static final boolean debug;
    
      public CondComp();
        Code:
           0: aload_0
           1: invokespecial #1                  // Method java/lang/Object."<init>":
    ()V
           4: return
    
      public void doIt();
        Code:
           0: return
    }
    

    可以看出,没有为println生成任何内容

    对于不相信的人来说,将debug设置为true也是一样的:

    Compiled from "CondComp.java"
    public class CondComp {
      static final boolean debug;
    
      public CondComp();
        Code:
           0: aload_0
           1: invokespecial #1                  // Method java/lang/Object."<init>":
    ()V
           4: return
    
      public void doIt();
        Code:
           0: getstatic     #2                  // Field java/lang/System.out:Ljava/
    io/PrintStream;
           3: ldc           #3                  // String Here we are
           5: invokevirtual #4                  // Method java/io/PrintStream.printl
    n:(Ljava/lang/String;)V
           8: return
    }
    

    我的理解是,即使static final变量在另一个类中,这也是正确的,但我从未尝试过

    这一特性记录在"unreachable statements"的JLS部分,该部分底部附近,以及"binary compatibility for final fields and constants"部分

  2. # 2 楼答案

    是的,它将被编译,其字节码将被发送到类文件中(至少由Oracle的编译器)。这很容易检查:

    javac YourClass.java
    javap -p -c YourClass
    

    。。。看看结果

    如果您使用Oracle的HotSpot运行它,并且如果它是代码中的HotSpot,如果它得到了JIT,我不会感到惊讶

    然而,在HotLickspoints out中添加final

    void fooBar() {
    
      final boolean debug = false;
    //^^^^^
    
      if (debug) System.out.println("will this be in the compile if debug is false?");
    
      // code for the method
    
    }
    

    。。。允许编译器不发出字节码。代码仍必须编译