Getting the name of the currently executing method

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

    We used this code to mitigate potential variability in stack trace index - now just call methodName util:

    public class MethodNameTest {
        private static final int CLIENT_CODE_STACK_INDEX;
    
        static {
            // Finds out the index of "this code" in the returned stack trace - funny but it differs in JDK 1.5 and 1.6
            int i = 0;
            for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
                i++;
                if (ste.getClassName().equals(MethodNameTest.class.getName())) {
                    break;
                }
            }
            CLIENT_CODE_STACK_INDEX = i;
        }
    
        public static void main(String[] args) {
            System.out.println("methodName() = " + methodName());
            System.out.println("CLIENT_CODE_STACK_INDEX = " + CLIENT_CODE_STACK_INDEX);
        }
    
        public static String methodName() {
            return Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX].getMethodName();
        }
    }
    

    Seems overengineered, but we had some fixed number for JDK 1.5 and were a bit surprised it changed when we moved to JDK 1.6. Now it's the same in Java 6/7, but you just never know. It is not proof to changes in that index during runtime - but hopefully HotSpot doesn't do that bad. :-)

提交回复
热议问题