Several methods of printing stack in Java

In java, the stack can be directly printed by tools such as eclipse, but when the eclipse tool cannot be used in some environments, it is necessary to know the stack, how to deal with it?

There are 3 methods to choose from:

method one:

copy code
package name.xu;
public class CallStack {
    public static void printCallStatck() {
        Throwable ex = new Throwable();
        StackTraceElement[] stackElements = ex.getStackTrace();
        if (stackElements != null) {
            for (int i = 0; i < stackElements.length; i++) {
                System.out.print(stackElements[i].getClassName()+"/t");
                System.out.print(stackElements[i].getFileName()+"/t");
                System.out.print(stackElements[i].getLineNumber()+"/t");
                System.out.println(stackElements[i].getMethodName());
                System.out.println("-----------------------------------");
            }
        }
    }
    
}
copy code

 

Method Two:

Exception e = new Exception("this is a log");
e.printStackTrace ();

 

Method three:

String fullStackTrace = org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e)

 

Method four:

Thread.currentThread().getStackTrace()

 

Personal recommendation, method one, reason: easy to use, fast

 

References:

1、http://blog.csdn.net/chief1985/article/details/4618492

2、http://www.cnblogs.com/flyme/archive/2012/04/10/2440029.html

3. http://stackoverflow.com/questions/1069066/get-current-stack-trace-in-java [ recommended to take a closer look ]

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326572547&siteId=291194637