0

For the Log purpose, I want to know the name of method at runtime.

Ex.

public void methodA(){
Log.e("INSIDE", "//some code here to get the name of methodA");
}

If I will get the name of method at runtime, it will reduce my repetitive task of inserting same log in different methods.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
  • Mention the reason for downvote please –  Apr 11 '13 at 19:20
  • possible duplicate of [Getting the name of the current executing method](http://stackoverflow.com/questions/442747/getting-the-name-of-the-current-executing-method) – Duncan Jones Apr 24 '14 at 08:51

1 Answers1

0

I assume this is Java... If that is the case, this returns the name of the method you are currently in.

String methodName = new Exception().getStackTrace()[0].getMethodName()

Be careful though, don't put this in a method, because then that will return the name of that method. You could also use this:

public String getMethodName() {
    return new Exception().getStackTrace()[1].getMethodName();
}

This observes the second element of the stack trace, returning the correct method name.

UPDATE:

Though the first does what it takes, this is nicer: doesn't involve creating a new object at least:

Thread.currentThread.getStackTrace()[1].getMethodName();

Warning I have to mention that all this however has an adverse impact on performance...

ppeterka
  • 20,583
  • 6
  • 63
  • 78