Getting the name of the currently executing method

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

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

22条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 04:13

    This can be done using StackWalker since Java 9.

    public static String getCurrentMethodName() {
        return StackWalker.getInstance()
                          .walk(s -> s.skip(1).findFirst())
                          .get()
                          .getMethodName();
    }
    
    public static String getCallerMethodName() {
        return StackWalker.getInstance()
                          .walk(s -> s.skip(2).findFirst())
                          .get()
                          .getMethodName();
    }
    

    StackWalker is designed to be lazy, so it's likely to be more efficient than, say, Thread.getStackTrace which eagerly creates an array for the entire callstack. Also see the JEP for more information.

提交回复
热议问题