开发者

How to know my code is running in "debug" mode in IDE?

开发者 https://www.devze.com 2023-04-04 23:25 出处:网络
How can I write the code which can behavior differently in run time under \"debug\" mode (e.g. invoked as \"Debug As Java Application\" in eclipse) from under \"run\" mode (e.g. invoked as \"Run As Ja

How can I write the code which can behavior differently in run time under "debug" mode (e.g. invoked as "Debug As Java Application" in eclipse) from under "run" mode (e.g. invoked as "Run As Java Application" in eclipse")? That is, for example, the code can print "Haha, you are in debug" when "Debug As Java Application" but print nothing when "Run As Java Application" (I don't want to append any args when invoking main method). Is there any general method to implement this which can work under any IDEs, like eclipse, Int开发者_高级运维elliJ etc?


I have implemented this as following. I examine the JVM parameters and look for one that is -Xdebug. Please see the code.

private final static Pattern debugPattern = Pattern.compile("-Xdebug|jdwp");
public static boolean isDebugging() {
    for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
        if (debugPattern.matcher(arg).find()) {
            return true;
        }
    }
    return false;
}

It works for me because eclipse executes application that is being debugged as separate process and connects to it using JDI (Java Debugging Interface).

I'd be happy to know whether this works with other IDEs (e.g. IntelliJ)


The difference between these modes is that in debug mode your IDE will connect to just executed application with a debugger (typically via binary socket). Having a debugger attached allows the IDE to discover breakpoints being hit, exceptions thrown, etc. This won't happen in normal mode.

There is no standard and easy to use way of distinguishing between debug and normal mode from Java code.

0

精彩评论

暂无评论...
验证码 换一张
取 消