Java “self” (static) reference

前端 未结 4 1221
感动是毒
感动是毒 2021-02-20 14:04

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

4条回答
  •  -上瘾入骨i
    2021-02-20 14:34

    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:

    public static String getCallingClassname() {
        return new RuntimeException().getStackTrace()[1].getClassName();
    }
    

    and then

    static Logger LOG = LoggerFactory.getLogger(Helper.getCallingClassname());
    

    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.

提交回复
热议问题