How can I get the current stack trace in Java?

前端 未结 21 3719
耶瑟儿~
耶瑟儿~ 2020-11-21 23:49

How do I get the current stack trace in Java, like how in .NET you can do Environment.StackTrace?

I found Thread.dumpStack() but it is not what I want -

21条回答
  •  萌比男神i
    2020-11-22 00:33

    StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
    

    The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

    A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().
    

    loop through StackTraceElement and get your desired result.

    for (StackTraceElement ste : stackTraceElements ) 
    {
        //do your stuff here...
    }
    

提交回复
热议问题