java 中打印调用栈

时间:2023-12-14 16:38:14
source-code:
public class A {
public A() {}
private static void printStackTrace() {
        StackTraceElement[] stackElements = new Throwable().getStackTrace();
        if(stackElements != null)
        {
            for(int i = 0; i < stackElements.length; i++)
            {
                System.out.println(""+ stackElements[i]); 
            }
        }
    }
    public void methodA() { methodB(); }
    public void methodB() { printStackTrace();}    
    public static void main(String[] argv) {
      A a = new A();
      a.methodA();
    }
  }
output:
A.printStackTrace(A.java:5)
A.methodB(A.java:16)
A.methodA(A.java:15)
A.main(A.java:20)
Note:
StackTraceElement.java
    public String toString() {
        return getClassName() + "." + methodName +
            (isNativeMethod() ? "(Native Method)" :
             (fileName != null && lineNumber >= 0 ?
              "(" + fileName + ":" + lineNumber + ")" :
              (fileName != null ?  "("+fileName+")" : "(Unknown Source)")));
    }
另外下面这些方法也可以:
new Exception("hello").printStackTrace();
Thread.getStackTrace()/Thread.getAllStackTraces() since jdk 1.5
Thread.currentThread().dumpStack()