Get the name of the current method being executed

19,279

Solution 1

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

Solution 2

You can try this:

public String getCurrentMethod(){
    try{
        throw new Exception("");
    }catch(Exception e){
        return e.getStackTrace()[0].toString();
    }
    return ""; // This never happens
}

It will return something like this:
ClassName.methodName():123

Solution 3

There are many answers for this if you search SO. This is a simple method

String name = new Object(){}.getClass().getEnclosingMethod().getName();

You should refer this post. Getting the name of the current executing method

Solution 4

On my device it's - Thread.currentThread().getStackTrace()[2].getMethodName()

(not [1] but [2])

Share:
19,279
Norbert
Author by

Norbert

Android application and software engineer.

Updated on June 16, 2022

Comments

  • Norbert
    Norbert almost 2 years

    Well what I am basically doing is an app which has many activities. I have a few friends with android phones and I gave them the app for testing. However, it sometimes goes into endless cycles and does strange behaviour which I am not able to understand due to their lack of programming experience and inability to dump the logcat in those particular moments.

    So what I need to do is to create a static always visible window, probably popup window, that shows in which method is the program now.

    So my question would be, which is the best way to achieve this functionality and how to retrieve the current method the App is in (it has several threads).

  • Joachim Sauer
    Joachim Sauer over 12 years
    Note: you don't need to throw an Exception to get it's stacktrace: new Exception().getStackTrace()[0] should work just fine.
  • Sky Kelsey
    Sky Kelsey over 12 years
    Of course. That's what I get for coding without compiling :)
  • matbrgz
    matbrgz about 11 years
    Note that each use creates a new anonymous class definition.
  • virgo47
    virgo47 over 7 years
    Check other question and my answer stackoverflow.com/a/8592871/658826 - this one gives you the right method name whatever the index is.