Java runtime gets the current run code class name, method name

Source: Internet
Author: User
Tags stack trace throwable stringbuffer

/*   
* 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.