1

I am implementing an Interface which holds a logging routine. Therefore i want to "cache" the logger inside of the interface.

It looks like this.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.function.Supplier;

interface ILogger {


    public static final Logger logger = LoggerFactory.getLogger(this.getClass().getName());


    default void debug() {
        // do sth with logger
    }
}

But i can't use this in a static method.

How can i store my logger in field, so i do not have to look it up everytime i use the debug method?

Aiko West
  • 791
  • 1
  • 10
  • 30

1 Answers1

4

Use a static class reference to get the name:

interface ILogger {
    Logger logger = LoggerFactory.getLogger(ILogger.class.getName());

    default void debug(String message) {
        logger.debug(message);
    }
}
teppic
  • 7,051
  • 1
  • 29
  • 35
  • Isn't that `public static final`? – Jin Kwon Jul 20 '23 at 07:47
  • @JinKwon `public static final` is the default for fields. See https://stackoverflow.com/questions/31144210/default-methods-in-interface-but-only-static-final-fields – teppic Jul 21 '23 at 02:19
  • That's not what I'm actually asking. Thanks. I'm talking about exposing the field as `public static final` via interface. – Jin Kwon Jul 21 '23 at 05:01