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