I am trying to get the caller class and method name inside a function in a Scala app. I am currently making use of the stack trace, but the performance has decreased. I am doing something like
stackTrace(CodeDepth).getClassName
stackTrace(CodeDepth).getMethodName
I have found the Java reflection to be a lot more faster, but i can only get the class name with
sun.reflect.Reflection.getCallerClass(CodeDepth).getName()
Is there a way to get the method name (and optionally the line number) via reflection? Maybe using Scala's reflection?
Thanks
Unfortunately, there is no non-expensive method to do this. There is a Java Enhancement Proposal to add a better alternative, but this doesn't help unless you can wait until Java 9 (and it isn't guaranteed to be included anyway).
On the other hand, is this really a hotspot in your code? This should only matter if it's called in a loop, and in this case you probably can call it once and cache the result.
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