Methods to get the name of a class name method

Source: Internet
Author: User

Below I present you and different ways to get the current Class:

    • Using Thread
    • Using GetClass ()

The simplest-to-get the name of the class where your code is being executed in are using the getClass() method present in Ev Ery Java object. Like here:

String clazz = This.getclass (). GetName ();

This works is only if executed in a Object, namely an instanciated class. If you try to execute the code above in a static method. It won ' t work. Even the keyword is this meaningless in a static method.

Also, the class returned by the above method may actually are a subclass of the class in which the method is defined. This is because subclasses inherit the methods of their parents; and GetClass () returns the actual runtime type of the object. To get the actual class in which a method is defined and use the method below also.

In a static method can instead use the following:

String clazz = Thread.CurrentThread (). Getstacktrace () [1].getclassname ();

Which uses the static method to getStackTrace() get the whole stacktrace. This method returns a array, where the first element (index 0) is the Getstacktrace () called and the second element ( Index 1) is the method your code are in.

A Similar trick can be used-find out the name of the The method currently executed:

String method = Thread.CurrentThread (). Getstacktrace () [1].getmethodname ();

It's exactly the same principle, just you dig out the name of the the The class.

             This . GetClass (). GetName ();              = Thread.CurrentThread (). Getstacktrace () [1].getmethodname ();

Methods to get the name of a class name method

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.