July 02, 2004

Get the name of currently executing method in Java

Just because I've seen so many posts on the net saying that you would have to parse out the name of the currently executing method of the stack trace print, throw exceptions or other bad implementations, here's a simple handy method to put in your unit test super class, works from j2sdk 1.4 and up. You probably don't want to use this in a production code if you cannot guarantee your target JVM and its settings because it might omit the stack information.


protected String getCurrentlyExecutingMethodName() {
  Throwable t = new Throwable();
  StackTraceElement[] elements = t.getStackTrace();
  if (elements.length <= 0) return "[No Stack Information Available]";
  // elements[0] is this method
  if (elements.length < 2) return null;
  return elements[1].getMethodName();
}

Posted by thoughts at July 2, 2004 11:49 AM | TrackBack
Comments

Here we are able to get the method name as a string.What if i want to get the currently exceuting method as a 'Method' object? so that i can use it to get the annotations associated with that method using getAnnotations().

Posted by: PBR at March 9, 2006 11:11 PM

Thanks for comments PBR. Just from the top of my head, it'd be something like this:

Class params[] = {};
Class executingClass = Class.forName(elements[1].getClassName() );
Method executingMethod = executingClass.getDeclaredMethod(elements[1].getMethodName(), params);

Posted by: alphageek at March 13, 2006 12:23 PM
Post a comment









Remember personal info?