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?
Asked
Active
Viewed 2,888 times
5
-
This topic is discussed in this thread: http://stackoverflow.com/questions/1109019/determine-if-a-java-application-is-in-debug-mode-in-eclipse – Peter Andersson Sep 13 '11 at 06:25
2 Answers
8
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)

Peter Lawrey
- 525,659
- 79
- 751
- 1,130

AlexR
- 114,158
- 16
- 130
- 208
-
+1: `debubg` ?? ;) You can set a static field for DEBUG instead of creating a static pattern as I wouldn't expect it to change. – Peter Lawrey Sep 13 '11 at 06:47
-
Thank you, @Peter Lawrey. It seems it worked for me because I added jdwp. I will fix this in my code. – AlexR Sep 13 '11 at 06:51
1
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.

Tomasz Nurkiewicz
- 334,321
- 69
- 703
- 674