Get the name of the calling class without using exceptions

Yes, getting the class name with an exception is a plausible solution, but I'm looking for something more elegant.

String className = new Exception().getStackTrace()[1].getClassName();

This will be used primarily for logging purposes and to ensure that cache keywords are specific to the component / calling class.

+3
source share
3 answers

a) there is no need to use Exception, you can do this: Thread.currentThread().getStackTrace()

b) whatever you try to do, do not do this. Sounds awful. I think you should look into the journal using AOP (here's a little tutorial that looks reasonable).

+8
source
Thread.currentThread().getStackTrace()
+3
source

In the Oracle JVM, you can use the non-standard sun.reflect.Reflection.getCallerClass (2). This is much faster, but should only be used with caution. (Since this is not a cross platform and may vary between versions of Java)

+3
source

All Articles