Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get caller class and method name

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

like image 734
sebi Avatar asked Sep 26 '22 16:09

sebi


1 Answers

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.

like image 185
Alexey Romanov Avatar answered Sep 29 '22 05:09

Alexey Romanov