I think your problem is, maybe you are moving up the stack upside down. In the returned element of value 0, the most recent call (which will be getStackTrace ()). I think you intend to do the following:
public static String getMethodName(final int depth) { final StackTraceElement[] ste = Thread.currentThread().getStackTrace(); return ste[1 + depth].getMethodName(); }
This will result in access to the most recent call on the stack (outside of the getStackTrace () call). For example, if you have a method:
public void foo() { System.out.println(getMethodName(0)); }
This will print "foo" with the above function implementation. Of course, you can also add some check on the bounds of the function, since it can easily go beyond the array.
M. jessup
source share