Is there a way to get the name of the currently executing method in Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
To get the name of the method that called the current method you can use:
This works on my MacBook as well as on my Android phone
I also tried:
but Android will return "getStackTrace" I could fix this for Android with
but then I get the wrong answer on my MacBook
Both of these options work for me with Java:
Or:
Technically this will work...
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
getEncosingMethod()
returnsjava.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 aSecurityException
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.It is required to use
getEnclosingConstructor()
for constructors. During blocks outside of (named) methods,getEnclosingMethod()
returnsnull
.An alternative method is to create, but not throw, an Exception, and use that object from which to get the stack trace data, since the enclosing method will typically be at index 0 - as long as the JVM stores that information, as others have mentioned above. This not the cheapest method, however.
From Throwable.getStackTrace() (this has been the same since Java 5 at least):
The snippet below assumes the class is non-static (because of getClass()), but that's an aside.
We used this code to mitigate potential variability in stack trace index - now just call methodName util:
Seems overengineered, but we had some fixed number for JDK 1.5 and were a bit surprised it changed when we moved to JDK 1.6. Now it's the same in Java 6/7, but you just never know. It is not proof to changes in that index during runtime - but hopefully HotSpot doesn't do that bad. :-)