0

In C++, you can use __FUNCTION_NAME__ to get the name of the function that contains __FUNCTION_NAME__.

Is there an equivalent in Java? It could, in Java, be possible to do something with this and reflection. Is there something simpler though?

4
  • did you try Thread.currentThread().getStackTrace()[1].getMethodName() ? Commented Jan 31, 2014 at 9:17
  • @Alessio: That's neat if a little expensive: and a candidate as an answer. Commented Jan 31, 2014 at 9:19
  • @Alessio this doesn't always work. See stackoverflow.com/questions/442747/… Commented Jan 31, 2014 at 9:22
  • you're right, I've used in a project and I didn't know that may not work Commented Jan 31, 2014 at 9:23

2 Answers 2

0

Thread.currentThread().getStackTrace() will usually contain the method you’re calling it from but there are pitfalls

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StackTraceElement.html

Sign up to request clarification or add additional context in comments.

Comments

0
Thread.currentThread().getStackTrace()[ste.length - 1 - depth].getMethodName();

depth = 0 (zero) will give current method

also

System.out.println((new Throwable()).getStackTrace()[0].toString());

Sample output:

com.junk.Junk3.main(Junk3.java:12)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.