Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

class

Right now I am doing something like this:

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

Is there a better way than using the name of the class (which is MasterController)? Maybe something generic?

like image 720
tim Avatar asked Dec 05 '25 13:12

tim


2 Answers

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);
like image 152
Drew Wills Avatar answered Dec 07 '25 02:12

Drew Wills


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();
    }
  }
}
like image 45
dpb Avatar answered Dec 07 '25 04:12

dpb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!