Java 预处理器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1344270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 16:11:30  来源:igfitidea点击:

Java Preprocessor

javaoptimizationpreprocessor

提问by twolfe18

If I have a boolean field like:

如果我有一个布尔字段,如:

private static final boolean DEBUG = false;

private static final boolean DEBUG = false;

and within my code I have statements like:

在我的代码中,我有以下语句:

if(DEBUG) System.err.println("err1");

if(DEBUG) System.err.println("err1");

does the Java preprocessor just get rid of the if statement and the unreachable code?

Java 预处理器是否只是摆脱了 if 语句和无法访问的代码?

回答by Adam Paynter

Most compilers will eliminate the statement. For example:

大多数编译器会消除该语句。例如:

public class Test {

    private static final boolean DEBUG = false;

    public static void main(String... args) {
        if (DEBUG) {
            System.out.println("Here I am");
        }
    }

}

After compiling this class, I then print a listing of the produced instructions via the javapcommand:

编译这个类后,我然后通过以下javap命令打印生成的指令列表:

javap -c Test
    Compiled from "Test.java"
    public class Test extends java.lang.Object{
    public Test();
      Code:
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."":()V
       4:   return

    public static void main(java.lang.String[]);
      Code:
       0:   return

    }

As you can see, no System.out.println! :)

如您所见,不System.out.println!:)

回答by Greg Hewgill

Yes, the Java compiler will eliminate the compiled code within ifblocks that are controlled by constants. This is an acceptable way to conditionally compile "debug" code that you don't want to include in a production build.

是的,Java 编译器将消除if由常量控制的块内的编译代码。这是有条件地编译您不想包含在生产版本中的“调试”代码的一种可接受的方式。