java 在不使用异常的情况下获取调用类的名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5375802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the name of a calling class without the use of Exceptions
提问by Peeter
Yes, getting the class name by using an exception 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.
这将主要用于记录目的并确保我的缓存关键字是特定于组件/调用者类的。
回答by Sean Patrick Floyd
a) no need to use Exception, you can do this: Thread.currentThread().getStackTrace()
a) 不需要使用异常,你可以这样做: 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 tutorialthat looks reasonable).
b) 无论你想做什么,都不要那样做。听起来真可怕。我想您应该研究通过 AOP 进行日志记录(这是一个看起来很合理的小教程)。
回答by Erik
Thread.currentThread().getStackTrace()
回答by Peter Lawrey
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)
在 Oracle JVM 上,您可以使用非标准 sun.reflect.Reflection.getCallerClass(2) 。这要快得多,但应谨慎使用。(因为它不是跨平台的,并且可以在 Java 版本之间改变)