Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java's method "know" its own name? [duplicate]

Tags:

java

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?

like image 258
James Raitsev Avatar asked Jan 24 '26 20:01

James Raitsev


2 Answers

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();
like image 141
Alex Gitelman Avatar answered Jan 27 '26 01:01

Alex Gitelman


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

like image 23
Bruno Avatar answered Jan 27 '26 02:01

Bruno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!