Getting the name of the currently executing method

前端 未结 22 2584
闹比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

    Util.java:

    public static String getCurrentClassAndMethodNames() {
        final StackTraceElement e = Thread.currentThread().getStackTrace()[2];
        final String s = e.getClassName();
        return s.substring(s.lastIndexOf('.') + 1, s.length()) + "." + e.getMethodName();
    }
    

    SomeClass.java:

    public class SomeClass {
        public static void main(String[] args) {
            System.out.println(Util.getCurrentClassAndMethodNames()); // output: SomeClass.main
        }
    }
    

提交回复
热议问题