Showing posts from May, 2013

Auto get CurrentMethodName very useful to logging on java programming

Getting the name of the current executing method /**  * 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.