用Java来编译调试代码 [英] Compile debug code in or out in Java
问题描述
我希望能够在发布产品时将调试代码(详细的日志记录等)编译出来,但要编译以进行调试。
I would like to be able to have my debug code (verbose logging, etc) compiled out when I make a production release, but compiled in for debugging.
我知道,如果我在常量上分支,编译器将删除该分支,这就是我想要的。所以我有一个类:
I understand that if I branch on a constant, the compiler will remove the branch, which is what I want. So I have a class:
class Debug {
public static final boolean ON=true;
}
而我的调试代码位于这样的分支中:
and my debug code is inside a branch like this:
if (Debug.ON) {
// Verbose / expensive logging goes here
}
我的问题是,我如何安排Debug.ON在编译时设置为true或false,而实际上不编辑源文件?
My question is, how do I arrange for Debug.ON to be set to true or false at compile time, short of actually editing the source file?
编辑:请注意,我不关心控制是否显示日志输出-我正在使用java.util.Logging,它可以解决这一问题。 。我更关心编译出昂贵的代码,这些代码正在准备永远不会得到输出的日志消息,或者进行生产模式中不需要的测量。
Note that I am not concerned with controlling whether log output appears or not - I am using java.util.Logging and it can take care of that. I am more concerned with compiling out any expensive code that is preparing log messages which will never get output, or taking measurements that are not needed in production mode.
我想我可能有一个蚂蚁目标,它可以从模板等生成源文件,但这看起来像是黑客。在C ++中,我可以定义可以与-D一起传递的预处理器符号-是否有Java等效项?还是其他更好的方法?
I guess I could have an ant target that makes the source file from a template or something, but it seems like a hack. In C++ I'd be able to define a pre-processor symbol which I could pass in with -D - is there any Java equivalent? Or some other better way?
推荐答案
您可以做的是拥有两个Jar或类文件。
What you can do is have two Jars or class files.
一个包含Debug类,其ON = true,另一个ON = false。
The one contains the Debug class with ON = true and the other ON = false.
然后,根据所需的调试状态进行编译时,应在类/ jar文件上包含DEBUG或在类/ jar文件上包含DEBUG。
Then when you compile depending on what debug state you want you include the DEBUG on class/jar file or the DEBUG off class/jar file.
这篇关于用Java来编译调试代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!