Java Print Current method name sample share _java

Source: Internet
Author: User

In C and C + + you can print the current function name in this way:

Copy Code code as follows:

printf ("%s", __func__);

In Java, however, there are two ways in which objects can be obtained from an object:

The first: through the thread class to get.

Copy Code code as follows:

System.out.println (Thread.CurrentThread (). Getstacktrace () [1].getmethodname ());
System.out.println (Thread.CurrentThread (). Getstacktrace () [1].getclassname ());

The second type is obtained by the Throwable class, and the second method can be extended, as long as the Throwable subclass can implement the function.

Copy Code code as follows:

System.out.println (New Throwable (). Getstacktrace () [0].getmethodname ());
System.out.println (New Throwable (). Getstacktrace () [0].getclassname ());

There are two ways to print out the current method name and the class name in it, but one drawback is the following index:

Copy Code code as follows:

Getstacktrace () [index]

What's the value, 0 or 1, or some other number, where the index of the two ways is written 0 and 1, which is used to remind yourself that it is not fixed and needs to be determined by testing itself. It is said that JDK versions may not be the same value. But I didn't test it myself.

JDK version of my test: Java version "1.7.0_17"

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.