Auto get CurrentMethodName very useful to logging on java programming

 * Get the method name for a depth in call stack. <br />
 * Utility function
 * @param depth depth in the call stack (0 means current method, 1 means call method, ...)
 * @return method name
public static String getMethodName(final int depth)
  final StackTraceElement[] ste = Thread.currentThread().getStackTrace();

  //System. out.println(ste[ste.length-depth].getClassName()+"#"+ste[ste.length-depth].getMethodName());
  // return ste[ste.length - depth].getMethodName();  //Wrong, fails for depth = 0
  return ste[ste.length - 1 - depth].getMethodName(); //Thank you Tom Tresansky

I use JRE 6 and gives me incorrect method name.
It works if I write ste[2 + depth].getMethodName().

0 is getStackTrace(),
1 is getMethodName(int depth) and
2 is invoking method.

Popular posts from this blog

เทคนิค ชนะ เกมเศรษฐี 14 ตารวด!!! ( Let's get Rich )

Using Google Chrome Inspect Element to Analyze the website

Easy way to download whole youtube play list and convert them to mp3