开发者

Is there a better way to get the current class variable in java?

Right now I am doing something like this:

 private static Logger logger = LoggerFactory
            .getLogger(MasterController.class);

I开发者_如何转开发s there a better way than using the name of the class (which is MasterController)? Maybe something generic?


How about this:

private final Logger logger = LoggerFactory.getLogger(getClass());

This approach avoids copy+paste errors.

I've read (don't remember where, was years ago) that Logger instances are terribly cheap and it doesn't matter if each instance of your class has its own logger.

But if you're not persuaded, and you want to keep the Logger instance static, then it should probably be both final and in uppercase, like so:

private static final Logger LOG = LoggerFactory.getLogger(MasterController.class);


The following link has an interesting approach:

http://www.rgagnon.com/javadetails/java-0402.html

Pasted in here for convenience:

public class ClassFromStatic {

  public static void main(java.lang.String[] args) {
    someStaticMethod();
  }

  public static void someStaticMethod() {
    System.out.println
       ("I'm in " + new CurrentClassGetter().getClassName() + " class");
  }

  public static class CurrentClassGetter extends SecurityManager {
    public String getClassName() {
      return getClassContext()[1].getName();
    }
  }
}


Not sure what you need but you can always call getClass() on an Object

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜