Reputation: 30994
I know about the (jvm) startup options to have the jvm wait until a debugger is attached - this is not what I mean here.
Is it possible from within Java code to also detect attachment of a debugger, so that I could e.g. write a "script" that is doing some stuff and then at a certain point make my app wait for the debugger?
Upvotes: 14
Views: 7922
Reputation: 257001
The consensus is: no. Java does not have the equivalent of:
But the consensus:
agrees that the best (non-minified) hack is:
public static boolean isDebuggerPresent() {
// Get ahold of the Java Runtime Environment (JRE) management interface
RuntimeMXBean runtime = java.lang.management.ManagementFactory.getRuntimeMXBean();
// Get the command line arguments that we were originally passed in
List<String> args = runtime.getInputArguments();
// Check if the Java Debug Wire Protocol (JDWP) agent is used.
// One of the items might contain something like "-agentlib:jdwp=transport=dt_socket,address=9009,server=y,suspend=n"
// We're looking for the string "jdwp".
boolean jdwpPresent = args.toString().contains("jdwp");
return jdwpPresent;
}
Which will have to suffice until Java officially adds one.
Upvotes: 5
Reputation: 6329
see Determine if a java application is in debug mode in Eclipse for detecting debugger
You could user TimerTask to poll for attachment
Upvotes: 0
Reputation: 5694
Depending on what you'd like to do, it might be worthwhile investigating the onthrow
JDWP sub-option. I haven't actually tried this ;-) but it seems like you could create a special exception type that you throw and catch to trigger JVM suspension. As shown in the linked examples, combining with launch
can provide for some interesting alternatives. Of course, the logic/workflow is different from what you've expressed, but it's something to think about...
Upvotes: 3
Reputation: 28094
No. The options are JVM options, and no Javacode is executed before the debugger connects. You can however let the app start, and spinloop on a getter for a variable, which you set from the debugger to let your app continue.
Upvotes: 6