Java“自我” (静态)参考
我正在以静态上下文方式寻找对 JAVA 中当前类的“自我”引用,如 PHP 范围解析运算符?
解决方案:超出范围?请注意,这与静态定义相比非常慢(慢了 300 倍):
static Logger LOG = LoggerFactory.getLogger(new RuntimeException().getStackTrace()[0].getClassName());
老式的方法是:
static Logger LOG = LoggerFactory.getLogger(<Classname>.class.getName());
还有其他选择吗?我正在寻找一种将记录器定义放入抽象类中的方法。记录器应该自行确定调用它的类。
I am looking for a "self" reference to the current class in JAVA in a static context manner like in PHP Scope Resolution Operator?
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());
The old-fashioned way would be:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果执行 1000 次,
则使用 Class.class.getName() 需要 36 毫秒,而使用这种方法则需要 60 毫秒。也许不值得担心太多。 ;)
The slightly faster
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. ;)
您不应该继承 logger。只需在每个类中声明记录器即可。
但如果你不想做这样有用的思考,就不要让它静态)
You should not inherit logger. Just declare logger in each class.
But if you don't want do such useful think, just don't make it static)
我认为没有任何替代方案与您问题中的两个方案有显着不同。
您可以创建一个像这样的辅助方法:
然后,
但这与原始版本一样昂贵。 (FWIW - 慢 300 倍可能不是主要问题,除非您有数千个这样的记录器。每个静态数据仅初始化一次......)
我个人更喜欢“老式”的方式。
I don't think there are any alternatives that are significantly different to the two in your question.
You could create a helper method like this:
and then
but that's as expensive as the original version. (FWIW - 300 times as slow is probably not a major concern, unless you have thousands of these loggers. Each of these statics is initialized just once ...)
My personal preference is for the "old fashioned" way of doing it.
您不需要使用其中任何一个。我觉得用起来方便的是:
//Logger
private static final Logger logger = LoggerFactory.getLogger(CreateEmployeeRecord.class or this.class);
在每个需要日志记录的类中执行此操作,并将括号中的类名更改为使用它的相应类。
You don't need to use any of those. What I find convenient to use is:
//Logger
private static final Logger logger = LoggerFactory.getLogger(CreateEmployeeRecord.class or this.class);
Do it in every class that needs logging, and change class name in bracket to corresponding class wherever it's being used.