How to get the current stack trace in Java

3 Answers

0 votes
import java.util.Arrays;
 
public class MyClass {
    public static void f2() {
        
        System.out.println("f2()");
    }
    
    public static void f1() {
        
        System.out.println("f1()");
        f2();
    }
    
    public static void main(String args[]) {
        
        f1();

        Thread currentThread = Thread.currentThread();
        
        StackTraceElement[] stackTrace = currentThread.getStackTrace();
        
        System.out.println(Arrays.toString(stackTrace));
    }
}
  
  
  
  
/*
run:
  
f1()
f2()
[java.base/java.lang.Thread.getStackTrace(Thread.java:1610), MyClass.main(MyClass.java:21)]
  
*/

 



answered Oct 27, 2023 by avibootz
0 votes
public class MyClass {
    public static void f2() {
        
        System.out.println("f2()");
    }
    
    public static void f1() {
        
        System.out.println("f1()");
        f2();
    }
    
    public static void main(String args[]) {
        
        f1();

        Thread currentThread = Thread.currentThread();
        
        StackTraceElement[] stackTrace = currentThread.getStackTrace();
        
        for (StackTraceElement element : stackTrace) {
            System.out.println(element);
        }
    }
}
  
  
  
  
/*
run:
  
f1()
f2()
java.base/java.lang.Thread.getStackTrace(Thread.java:1610)
MyClass.main(MyClass.java:21)
  
*/

 



answered Oct 27, 2023 by avibootz
0 votes
public class MyClass {
    public static void f2() {
        
        System.out.println("f2()");
    }
    
    public static void f1() {
        
        System.out.println("f1()");
        f2();
    }
    
    public static void main(String args[]) {
        
        f1();

        Thread currentThread = Thread.currentThread();
        
        Throwable t = new Throwable();
        StackTraceElement[] stackTrace = t.getStackTrace();
        
        for (StackTraceElement element : stackTrace) {
            System.out.println(element);
        }
    }
}
  
  
  
  
/*
run:
  
f1()
f2()
MyClass.main(MyClass.java:19)
  
*/

 



answered Oct 27, 2023 by avibootz

Related questions

...