Java print current method name sample share

  • 2020-04-01 02:58:06
  • OfStack

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


printf("%s",__func__);

But in Java there is no such statement, everything is an object, to get from an object, can be divided into two ways:

The first is through the Thread class.


System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());
System.out.println(Thread.currentThread().getStackTrace()[1].getClassName());

The second method is obtained by the Throwable class. The second method can be extended to any subclass of Throwable.


System.out.println(new Throwable().getStackTrace()[0].getMethodName());
System.out.println(new Throwable().getStackTrace()[0].getClassName());

These two methods can print the name of the current method and the name of the class, but there is a disadvantage of the following index:


getStackTrace()[index]

What value to take, 0 or 1 or whatever, in this case the two ways of writing index as 0 and 1, just to remind yourself that it's not fixed, you have to test it out. It is said that different versions of the JDK may have different values. But I haven't tested it myself.

JDK version I tested: Java version "1.7.0_17"


Related articles: