Is there a way to get the name of the currently executing method in 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.
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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With