2

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?

Dante WWWW
  • 2,729
  • 1
  • 17
  • 33
  • Add a breakpoint where you want it, right click the break point node (in the gutter of margin) and select "Breakpoint Properties"...Fill out the details... – MadProgrammer Mar 05 '15 at 04:05
  • @MadProgrammer it's not about where I should put the condition, it's about what I should write in the condition box. It requires an expression which returns a boolean; so I am actually asking, how should I check an array of StackTraceElement for desired item in that condition. – Dante WWWW Mar 05 '15 at 05:04
  • @coolcfan I add a proof of concept in my answer. – Ortomala Lokni Mar 19 '15 at 19:34

2 Answers2

1

For my specific requirement, using lambda and stream in Java 8:

Arrays.asList(Thread.currentThread().getStackTrace())
      .stream()
      .anyMatch(e -> e.getMethodName().contains("fetchByABC"))
Dante WWWW
  • 2,729
  • 1
  • 17
  • 33
0

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().

Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240
  • I decide to accept this answer although I finally went to Eclipse to debug the code since it's in a third-party library. Pasting the method body into Netbeans might also work. – Dante WWWW Mar 20 '15 at 05:21