How do I get the method name from within that method?

前端 未结 4 1789
天命终不由人
天命终不由人 2021-02-06 10:02

I am trying to create a function that returns the method name from within that method:

  public static String getMethodName(final int depth)
  {
    final StackT         


        
4条回答
  •  有刺的猬
    2021-02-06 10:35

    I think your problem maybe you are accessing the stack upside down. In the returned value element 0 is the most recent call (which would be getStackTrace()). I think what you are intending to do is:

    public static String getMethodName(final int depth) {
      final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
      return ste[1 + depth].getMethodName();
    }
    

    This will access the most recent call in the stack (outside of the call to getStackTrace()). For example if you have a method:

    public void foo() {
      System.out.println(getMethodName(0));
    }
    

    This will print "foo" with the above implementation of the function. Of course you may also want to add some bounds checking to the function since it could easily go outside the array.

提交回复
热议问题