Java“自我” (静态)参考 [英] Java "self" (static) reference
问题描述
我正在以静态上下文的方式寻找JAVA中当前类的自我引用,如 PHP范围解析运算符?
I am looking for a "self" reference to the current class in JAVA in a static context manner like in PHP Scope Resolution Operator?
解决方案:超出范围?请注意,这与静态定义真正慢(按因子300)进行比较:
Solution: Break out of scope? BEWARE, this is compared to a static definition really slow (by factor 300):
static Logger LOG = LoggerFactory.getLogger(new RuntimeException().getStackTrace()[0].getClassName());
老式的方式是:
static Logger LOG = LoggerFactory.getLogger(<Classname>.class.getName());
还有其他选择吗?我正在寻找一种将记录器定义放在抽象类中的方法。记录器应该确定它自己调用的类。
Are there any alternatives? I'm looking for a way to put the logger definition in an abstract class. The logger should determine the class it's being called from by itself.
推荐答案
稍微快一点
static final Logger LOG = LoggerFactory.getLogger(
Thread.currentThread().getStackTrace()[0].getClassName());
如果这样做1000次,使用Class.class.getName()和60需要36 ms ms这样做。也许它不值得担心太多。 ;)
If you do this 1000 times it will take 36 ms using Class.class.getName() and 60 ms doing it this way. Perhaps its not worth worrying about too much. ;)
这篇关于Java“自我” (静态)参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!