Getting the name of the currently executing method

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

    January 2009:
    A full code would be (to use with @Bombe's caveat in mind):

    /**
     * Get the method name for a depth in call stack. 
    * Utility function * @param depth depth in the call stack (0 means current method, 1 means call method, ...) * @return method name */ public static String getMethodName(final int depth) { final StackTraceElement[] ste = Thread.currentThread().getStackTrace(); //System. out.println(ste[ste.length-depth].getClassName()+"#"+ste[ste.length-depth].getMethodName()); // return ste[ste.length - depth].getMethodName(); //Wrong, fails for depth = 0 return ste[ste.length - 1 - depth].getMethodName(); //Thank you Tom Tresansky }

    More in this question.

    Update December 2011:

    bluish comments:

    I use JRE 6 and gives me incorrect method name.
    It works if I write ste[2 + depth].getMethodName().

    • 0 is getStackTrace(),
    • 1 is getMethodName(int depth) and
    • 2 is invoking method.

    virgo47's answer (upvoted) actually computes the right index to apply in order to get back the method name.

提交回复
热议问题