Gets the class name, method name, and line number of the currently running code

Source: Internet
Author: User
Tags stack trace throwable stringbuffer
Package com.segsec.gisap.webservice; 
 * * 1. Gets the class name, method name, and line number of the currently running code, mainly through the Java.lang.StackTraceElement class * * 2.
 * [1] Obtain the caller's method name, with the new throwable * String _methodname = new Exception (). Getstacktrace () [1].getmethodname ();
 * [0] Obtains the current method name, with the 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 (); }

}

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.