Getting the name of the currently executing method

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

    To get the name of the method that called the current method you can use:

    new Exception("is not thrown").getStackTrace()[1].getMethodName()
    

    This works on my MacBook as well as on my Android phone

    I also tried:

    Thread.currentThread().getStackTrace()[1]
    

    but Android will return "getStackTrace" I could fix this for Android with

    Thread.currentThread().getStackTrace()[2]
    

    but then I get the wrong answer on my MacBook

提交回复
热议问题