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

Now I am doing something like this:

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

Is there a better way than using a class name (which is a MasterController)? Maybe something in common?

+3
source share
3 answers

How about this:

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

This approach avoids copy and paste errors.

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

But if you are not convinced, and you want the Logger instance to be static, it should be both final and uppercase, for example:

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

:

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

:

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();
    }
  }
}
+1

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

-2
source

Source: https://habr.com/ru/post/1730296/


All Articles