JAVA如何在任意方法中打印当前线程栈信息(StackTrace)

public class Test {
 
 //Invoke the static method where you want to print a stack trace
 public static void printStackTrace(Class cls) {
        StackTraceElement[] elements = (new Throwable()).getStackTrace();
        StringBuffer buf = new StringBuffer();
        buf.append("Stack for " + cls.getName() + ":");
        for(int i=0; i<elements.length; i++) {
         buf.append("/n    "
           + elements[i].getClassName()
           + "."
           + elements[i].getMethodName()
           + "("
           + elements[i].getFileName()
           + ":"
           + elements[i].getLineNumber()
           + ")");
        }
        System.out.println(buf.toString());
 }
    public static void main(String args[])   {
     //An example to show how to invoke it
     printStackTrace(Test.class);
    }
}

你可能感兴趣的:(java,String,Class)