In C and C++, you can print the current function name like this:
Copy the code code as follows:
printf("%s",__func__);
But there is no such saying in Java. Everything is an object, and it must be obtained from an object. There are two ways:
The first one: Obtain it through the Thread class.
Copy the code code as follows:
System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());
System.out.println(Thread.currentThread().getStackTrace()[1].getClassName());
The second method is obtained through the Throwable class. The second method can be extended. As long as it is a subclass of throwable, the function can be implemented.
Copy the code code as follows:
System.out.println(new Throwable().getStackTrace()[0].getMethodName());
System.out.println(new Throwable().getStackTrace()[0].getClassName());
Through these two methods, the current method name and the class name can be printed out, but there is a drawback: the following index:
Copy the code code as follows:
getStackTrace()[index]
What value should be taken, 0 or 1 or other values? Here the indexes of the two methods are written as 0 and 1 respectively, just to remind yourself that it is not fixed and needs to be determined by yourself through testing. It is said that the value may be different depending on the JDK version. But haven't tested it myself.
The JDK version I used for testing: java version "1.7.0_17"