Getting the name of the currently executing method

前端 未结 22 2751
闹比i
闹比i 2020-11-22 03:33

Is there a way to get the name of the currently executing method in Java?

22条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 04:13

    An alternative method is to create, but not throw, an Exception, and use that object from which to get the stack trace data, since the enclosing method will typically be at index 0 - as long as the JVM stores that information, as others have mentioned above. This not the cheapest method, however.

    From Throwable.getStackTrace() (this has been the same since Java 5 at least):

    The zeroth element of the array (assuming the array's length is non-zero) represents the top of the stack, which is the last method invocation in the sequence. Typically, this is the point at which this throwable was created and thrown.

    The snippet below assumes the class is non-static (because of getClass()), but that's an aside.

    System.out.printf("Class %s.%s\n", getClass().getName(), new Exception("is not thrown").getStackTrace()[0].getMethodName());
    

提交回复
热议问题