Home > OS >  How to get stack trace from the caller in Java
How to get stack trace from the caller in Java

Time:07-01

In Java, I want to get the stack trace of how the calls were made to which methods. How can I achieve that?

For example, my call stack is:

class Example {
   public void init() {
      func1();
      // TODO : now here I want to print the stack trace that it went from:
      // func1
      // func2
      // func3
   }
   public void func1() {
      func2();
   }
   public void func2() {
      func3();
   }
   public void func3() {
      // some code here
   }
    

}

CodePudding user response:

This is what you want

class Example {
  public void init() {
     func1();
     // TODO : now here I want to print the stack trace that it went from:
     try { throw new Throwable("Debugging") } catch (Throwable t) { t.printStackTrace(); }
     // or
     System.out.println(Arrays.toString(Thread.currentThread().getStackTrace()));
     // func1
     // func2
     // func3
  }
  public void func1() {
     func2();
  }
  public void func2() {
     func3();
  }
  public void func3() {
     // some code here
  }
}

CodePudding user response:

Use a IDE and make use of breakpoints. Personally, I use IntelliJ. You can add breakpoints to your code. Breakpoints will make your program halt when they get hit. At that time you can see call stack in Debugger window under IntelliJ.
IntelliJ provides great support for debugging, and also provides easy tutorials to get started with IntelliJ Debugger Tool.

  •  Tags:  
  • java
  • Related