Determine current method in Java

A rather strange way to determine the method, where you currently are, but it works:

1
2
3
4
5
6
7
8
9
private String getCurrentMethodName() {
   List stackTraceList = Arrays.asList((new Throwable()).getStackTrace());
   for (Iterator it=stackTraceList.iterator();it.hasNext();) {
      StackTraceElement ste = (StackTraceElement) it.next();
      if (!ste.getClassName().equals(this.getClass().getName())) 
         return ste.getClassName().concat(".").concat(ste.getMethodName());
   }
   return null;
}

I implemented it the way that the first method from the stacktrace is returned that does not belong to the class, where this code resides. So it is possible to use this code for example in an own logging class to augment the logging messages with the method name.

You can find another example here: http://dev.kanngard.net/

Share this:
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Buzz
  • LinkedIn
  • Technorati

Leave a Reply