Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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, IntelliJ etc?

like image 623
Eric Jiang Avatar asked Sep 13 '11 06:09

Eric Jiang


2 Answers

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)

like image 200
AlexR Avatar answered Oct 13 '22 13:10

AlexR


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.

like image 41
Tomasz Nurkiewicz Avatar answered Oct 13 '22 14:10

Tomasz Nurkiewicz