Java is equivalent to __func__

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

Each time a function is called, it will print:

 someFunc 

What is the java equivalent?

I found

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

and

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

But it just seems funny, is there an easier way?

+4
source share
5 answers

No, there is no simpler way. Since Java does not have a macro facility, there is nothing that is directly equivalent to the C ++ version.

+6
source

With some configuration, you can create something like log4j with a template that includes the method name (and any other data you want), then all you need to do is something like:

 private static final Logger log = Logger.getLogger(MyClass.class); void someMethod() { log.info("text"); } 

The advantage here is that you perform the setup once, and then you can reuse the recorder in as many places as you want.

+2
source

You can use log4j and use% M patter to display the method name when necessary -> http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

However, the documentation has the following warning:

WARNING Creating the location of the caller is extremely slow information and should be avoided if running speed is not an issue.

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

On the other hand, log4j is very configurable, and you can add the output of the method name to a subset of your code that is not performance critical.

+2
source

Answer: No.

By the way, the two approaches you 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 pointed out, throwing an Exception to grab a stacktrace is an expensive operation in Java, so you have to do this WITH WARUTION.

+2
source

Another ridiculous way to get the java.lang.reflect.Method inclusion method:

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

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

I would like to have a more built-in way to get metadata at runtime ...

0
source

Source: https://habr.com/ru/post/1345300/


All Articles