27

I was wondering if there is a way to know the method name being executed at run time?

For instance, inside a private void doSomething (String s) method, I'd like to know that I am executing the doSomething (String s) method.

2
  • 1
    This really isn't something your code should require. I'd very much advise rethinking your design so that you don't need it. Commented Jan 9, 2011 at 20:28
  • 1
    If you are inside that method you already know the name, right? :) If you want to know the caller method's name, Jigar's answer below is the one you are looking for. Just use 1 instead of 0 as index. Commented Jan 9, 2011 at 20:28

3 Answers 3

66

Since JDK1.5, you don't need an Exception to get the StackTrace,
you can get it with Thread.currentThread().getStackTrace()]:

   public class Test2 {
     public static void main(String args[]) {
        new Test2().doit();
     }
     public void doit() {
        System.out.println(
           Thread.currentThread().getStackTrace()[1].getMethodName()); // output : doit
     }
   }
Sign up to request clarification or add additional context in comments.

10 Comments

This is a better solution, as you don't have to create the exception to get the stack.
Not sure why this isn't working for me...it prints out "getStackTrace" for me - using Java 1.5
@Zack Macomber, What is the output : StackTraceElement [] ste = Thread.currentThread().getStackTrace(); for (StackTraceElement s : ste) { System.out.println(s); } , are you using a Sun JRE ?
@RealHowTo - I was able to use '[2]' instead of '[1]' to get the method name - I use IBM's RSA so I think I may be using IBM's version of Java
I am trying to print the method name in android activity methods . I had to use Thread.currentThread().getStackTrace()[2].getMethodName()
|
10
System.out.println(new Exception().getStackTrace()[0].getMethodName());

Also See

4 Comments

useGetStacktrace()[1] to get the calling methods name. A bit more useful :)
@Daniel, is that what was asked for? Note that 1) there is no guarantee that the stacktrace is accurate, and 2) that this has previously been a very expensive operation. It should be better in recent JVM's.
Really? When would it possible that you get an inaccurate stack trace occurs? Or is it just not guaranteed you get one? I never had these problems.
It think it's important to precise that this solution is only good for JDK >= 1.4 and < 1.5. For JDK >= 1.5 you don't have to instanciate a new Exception each time, which saves resources (checkout RealHowTo's answer above).
-2
Method lastMethodCalled = this.getClass().getEnclosingMethod();

1 Comment

This doesn't do what he was asking for. See this link

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.