Search code examples
javadebuggingnetbeansconditional-breakpoint

Conditional Breakpoints on Call Stack with Netbeans and Java


Just like this question, when debugging an application, I want to let the application pause at a breakpoint only when the current call stack has a certain method. However, I'm using Netbeans.

In Java the current call stack could be obtained in several ways, like

Thread.currentThread().getStackTrace()

which returns an array of stack trace elements.

Is it possible to iterate through the array (or converted list), check the method names and return a boolean in just one line?

Or, if I need to write a method which checks the array and returns the boolean based on existence of interested method, where should I put it?


Solution

  • You can add a private method testing conditions on the stack and call it from the conditional breakpoint. Here is a proof of concept:

    public class DebugStack {
        private int x = 0;
        private void m1(){
            x++;
            m2();
        }
        private void m2(){
            x+=3;         
        }
        private boolean insideMethod(String methodName){
            for (StackTraceElement stackTrace : Thread.currentThread().getStackTrace()) {
                if (stackTrace.getMethodName().equals(methodName)) {
                    return true;
                }
            }
            return false;
        }
        public static void main(String[] args) {
            DebugStack dbg = new DebugStack();
            dbg.m1();
            dbg.m2();
    
        }
    }
    

    If you put a conditional breakpoint inside m2() with this.insideMethod("m1") as a condition the application will pause at the breakpoint only when m2() is called from within m1().