/*
* 1. Gets the class name, method name, and line number of the currently running code, mainly through the Java.lang.StackTraceElement class
*
* 2. Get caller, current method name
* [1] Get the caller's method name, same as new Throwable
* String _methodname = new Exception (). Getstacktrace () [1].getmethodname ();
* [0] Get the current method name, same as new Throwable
* String _thismethodname = new Exception (). Getstacktrace () [0].getmethodname ();
* */
Public class Stacktraceelementtest {
Public static void Main (string[] args) {
System.out.println ("line1:" + new Throwable (). Getstacktrace () [0].getlinenumber ()];
System.out.println ("line2:" + getlineinfo ());
System.out.println ("line3:" + gettraceinfo ());
stacktraceelement ste1 = null;
stacktraceelement[] Stearray = Thread.CurrentThread (). Getstacktrace ();
int stearraylength = stearray.length;
String s = null;
//Output all related info of the existing stack traces
if (stearraylength==0) {
System.err.println ("No Stack Trace.");
} else {
for (int i=0; i<stearraylength; i++) {
System.out.println ("Stack trace-" + i);
ste1 = stearray[i];
s = ste1.getfilename () + ": line" + Ste1.getlinenumber ();
System.out.println (s);
}
}
}
Public static String Gettraceinfo () {
stringbuffer sb = new StringBuffer ();
stacktraceelement[] Stacks = new Throwable (). Getstacktrace ();
int stackslen = stacks.length;
Sb.append ("Class:"). Append (Stacks[1].getclassname ())
. Append ("; Method: "). Append (Stacks[1].getmethodname ())
. Append ("; Number: "). Append (Stacks[1].getlinenumber ());
return sb.tostring ();
}
Public static String Getlineinfo () {
stacktraceelement ste = new Throwable (). Getstacktrace () [1];
return Ste.getfilename () + ": line" + Ste.getlinenumber ();
}
}
Java runtime gets the current run code class name, method name