java equivalent to __func__
Asked Answered
S

5

6
#include <stdio.h>
void someFunc(void) {
  printf("%s\n"), __func__);
}

Each time the function is called it will print:

someFunc

What is the java equivalent?

I have found

(new Exception()).getStackTrace()[0].getMethodName()

And

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

But these just seem ridiculous, is there an easier way?

Sofiasofie answered 26/3, 2011 at 0:11 Comment(1)
Don't expect Java to have direct equivalents to all C++ constructs, or vice-versa.Renoir
D
7

No, there's no easier way. As Java doesn't have a macro facility, there's nothing directly equivalent to the C++ version.

Drilling answered 26/3, 2011 at 0:13 Comment(1)
Technically speaking, __func__ is not a preprocessor macro - the C or C++ preprocessor has no concept of functions. It's implemented by the compiler itself.Cockscomb
P
2

With a bit of configuration you could set up something like log4j with a pattern that includes the method name (and any other details you want), then all you have to do is something like:

private static final Logger log = Logger.getLogger(MyClass.class);

void someMethod() {
    log.info("text");
}

The benefit here is that you do the setup once, and then you can reuse the logger in as many different places as you want.

Peake answered 26/3, 2011 at 0:23 Comment(0)
D
2

You may use log4j and use %M patter to output the method name, when needed -> http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

The documentation, though, has this warning:

WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.

They probably use the trick similar to your (new Exception()).getStackTrace()[0].getMethodName(), but this is a very slow call to use in every log statement.

On the other hand log4j is highly customizable and you may add the method name output to a subset of your code that is not performance critical.

Dimitri answered 26/3, 2011 at 0:27 Comment(0)
R
2

The answer is No.

Incidentally, the two approaches you've found are essentially equivalent. If t is the current thread, then t.getStackTrace() works by creating an instance of Exception and calling getStaceTrace() on it.

As others have noted, creating an Exception to capture the stacktrace is an expensive operation in Java, so you should do this WITH CAUTION.

Renoir answered 26/3, 2011 at 0:31 Comment(0)
W
0

Another ridiculous way for receiving the java.lang.reflect.Method of the enclosing method would be:

void someMethod() {
    class A{}
    Method thisMethod = A.class.getEnclosingMethod();
}

This way you can not only find the method name, but also other interesting features of the method such as annotations, parameterized types, etc.

I wish there has been a more built-in way of acquiring metadata at runtime...

Willms answered 9/4, 2019 at 17:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.