3

Possible Duplicate:
Getting the name of the current executing method

Is there a way in Java for a given method to know its own name? If so, how can it be referenced from inside the method?

Community
  • 1
  • 1
James Raitsev
  • 92,517
  • 154
  • 335
  • 470

2 Answers2

5

You can determine it by analyzing stack trace. But it may carry quite significant performance penalty. In AOP universe you can also have aspect that will determine method name and store it in some kind of context.

In stack trace method you would do something like

Exception e = new Exception();
e.fillInStackTrace();
e.getStackTrace()[0].getMethodName();

or (as suggested in comment)

Thread.currentThread().getStackTrace()[0].getMethodName();
Alex Gitelman
  • 24,429
  • 7
  • 52
  • 49
  • 2
    You don't need to create a new exception. `Thread` can return a stack trace using `getStackTrace()`. – Steve Kuo Sep 11 '12 at 00:54
  • 1
    Actually, Thread.currentThread().getStackTrace()[0].getMethodName(); will return "getStackTrace". getStackTrace()[1] is probably what you want - the name of the routine which is calling getStackTrace(). In my case, I wanted to know the name to the routine which called the current routine, so [2] was my answer. – rcprcp Jun 17 '18 at 18:07
  • @rcprcp Code above will have to be placed in method that wants to know its name. You will always need to adjust stacktrace if you put more utility methods on top of it. When I have to do something like this, I just pass a parameter that tells the amount of adjustment. – Alex Gitelman Jul 25 '18 at 00:44
  • @AlexGitelman--(1) How do I "adjust stacktrace"? (2) What do you mean by "put more utility methods on top of it" (3) What sort of parameter and its value tells the "amount of adjustment"? – DSlomer64 Jun 14 '19 at 19:28
  • @DSlomer64 If your method is `foobar()` and you place the code above in it, you take stack element at offset 0 to get `foobar`. But if you create utility method `getMethodName()` that you call from `foobar()` then offset will be 1 since at offset 0 you will find `getMethodName`. If you have more nested methods, you will have to adjust more. – Alex Gitelman Jun 15 '19 at 20:16
4

The first element of the stack trace (Thread.currentThread().getStackTrace(), see this question) should tell you in which method you currently are at runtime.

Community
  • 1
  • 1
Bruno
  • 119,590
  • 31
  • 270
  • 376