Get the name of a calling class without the use of Exceptions
Yes, getting the class name by using an exc开发者_如何转开发eption is a plausible solution, but I'm looking for something that is a bit more elegant.
String className = new Exception().getStackTrace()[1].getClassName();
This will be used mainly for logging purposes and making sure my cache keywords are component/caller-class specific.
a) no need to use Exception, you can do this: Thread.currentThread().getStackTrace()
b) whatever you are trying to do, don't do it that way. That sounds awful. I guess you should be looking into logging via AOP (here's a small tutorial that looks reasonable).
Thread.currentThread().getStackTrace()
On the Oracle JVM you can use the non-standard sun.reflect.Reflection.getCallerClass(2) . This is much faster but should only be used with care. (As it is not cross platform and could change between versions of Java)
精彩评论