Static methods are not associated with a specific instance and cannot reference this. To obtain the current class name, there is no direct method.
The following methods can be used for data query and testing:
1 public static void testGetClassName ()
2 {
3 // Method 1: Use the SecurityManager protection method getClassContext ()
4 String clazzName = new SecurityManager ()
5 {
6 public String getClassName ()
7 {
8 return getClassContext () [1]. getName ();
9}
10}. getClassName ();
11 System. out. println (clazzName );
12 // Method 2: getStackTrace () through the Throwable Method ()
13 String clazzName2 = new Throwable (). getStackTrace () [1]. getClassName ();
14 System. out. println (clazzName2 );
15 // method 3: analyze the Anonymous class name ()
16 String clazzName3 = new Object (){
17 public String getClassName ()
18 {
19 string clazzname = This. getclass (). getname ();
20 return clazzname. substring (0, clazzname. lastindexof ('$ '));
21}
22}. getclassname ();
23 system. Out. println (clazzname3 );
24}
Call 0.1 million times respectively,
Method 1: 219 Ms
Method 2: 953 Ms
Method 3: 31 Ms
Comparison:
1) method 1. Do you have any restrictions?
2) method 2 gets the call stack through the exception mechanism, with the worst performance, but can provide functions not available for other methods, as well as the method name and row number; however, this is not a common practice;
3) method 3 is just a brief analysis of the name of the anonymous class. Obviously, it is much simpler. In fact, the performance is also the highest;
----------------------------------
--------------------------------------
Dynamically Retrieve the Class Name of the current class in the static method or variable in java
Java get class name
In java, the Class Name of the current class is dynamically obtained in the static method or the class name of the current class is dynamically obtained and paid to a static variable. A typical column is when logging using logger, we need to write the class names of the classes that require log, for example:
Java code:
Protected static final Log logger = LogFactory. getLog (Test. class );
In this way, the write is relatively rigid, and the class name of the current class can be dynamically obtained through the Anonymous class method, as shown below:
Protected static final Log logger = LogFactory. getLog (new Object (){
// Obtain the current class name from the static method.
Public String getClassName (){
String className = this. getClass (). getName ();
Return className. substring (0, className. lastIndexOf ('$ '));
}
}. GetClassName ());