Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the name of the currently executing method

Is there a way to get the name of the currently executing method in Java?

like image 643
Omar Kooheji Avatar asked Jan 14 '09 12:01

Omar Kooheji


People also ask

How can I find the method that called the current method Java?

Getting Name of Current Method inside a method in JavagetEnclosingMethod() returns a Method object representing the immediately enclosing method of the underlying class. StackTraceElement. getMethodName()-The java. lang.

What is method name in C#?

Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class. Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method.

What is System reflection?

Reflection is the process of describing the metadata of types, methods and fields in a code. The namespace System.Reflection enables you to obtain data about the loaded assemblies, the elements within them like classes, methods and value types. Some of the commonly used classes of System.Reflection are: Class.


2 Answers

Technically this will work...

String name = new Object(){}.getClass().getEnclosingMethod().getName(); 

However, a new anonymous inner class will be created during compile time (e.g. YourClass$1.class). So this will create a .class file for each method that deploys this trick. Additionally, an otherwise unused object instance is created on each invocation during runtime. So this may be an acceptable debug trick, but it does come with significant overhead.

An advantage of this trick is that getEnclosingMethod() returns java.lang.reflect.Method which can be used to retrieve all other information of the method including annotations and parameter names. This makes it possible to distinguish between specific methods with the same name (method overload).

Note that according to the JavaDoc of getEnclosingMethod() this trick should not throw a SecurityException as inner classes should be loaded using the same class loader. So there is no need to check the access conditions even if a security manager is present.

Please be aware: It is required to use getEnclosingConstructor() for constructors. During blocks outside of (named) methods, getEnclosingMethod() returns null.

like image 55
Devin Avatar answered Oct 05 '22 21:10

Devin


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

Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this thread is permitted to return a zero-length array from this method.

like image 38
Bombe Avatar answered Oct 05 '22 20:10

Bombe