Getting the name of the currently executing method

前端 未结 22 2613
闹比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:25

    Most answers here seems wrong.

        public static String getCurrentMethod() {
                return getCurrentMethod(1);
        }
        public static String getCurrentMethod(int skip) {
                return Thread.currentThread().getStackTrace()[1 + 1 + skip].getMethodName();
        }
    

    Example:

        public static void main(String[] args) {
                aaa();
        }
    
        public static void aaa() {
                System.out.println("aaa  -> "  + getCurrentMethod( ) );
                System.out.println("aaa  -> "  + getCurrentMethod(0) );
                System.out.println("main -> "  + getCurrentMethod(1) );
        }
    

    Outputs:

    aaa  -> aaa
    aaa  -> aaa
    main -> main
    

提交回复
热议问题