Search code examples
javainterfacedefault-method

How to simulate static variable in Java interface default method?


To easily enable logging for plurality of my project classes, I have decided to abuse the new default keyword to create a simple method trait for my classes:

  default void Log(Level lvl, String msg) {
    Logger log = Logger.getLogger(this.getClass().getName()); 
    //Log something
  }

What I really dislike about this is the need to get the log every time. Were I working with C++, I'd declare:

static Logger log = ...;

Every other call to the function, the logger would already be initialized in the variable. In normal classes, I use this pattern to simulate static variable:

class A {
    //By default, this is null until needed
    private Obj cached_obj = null;
    public void doSomethingWithObj(Something thing) {
        //Once needed, it only initialises once
        if(cached_obj==null)
            cached_obj = Obj.generateObj();
        cached_obj.doSomething(thing);
    }
}

But this is not possible with interface. Interface cannot have any properties.

So is there some other workaround, or is Java going to hold my performance back again?


Solution

  • There's really no way to cache this as, by design, interfaces have no state associated with them.

    That being said, this may not as big of an issue as it appears at first glance.

    If you are logging enough to make it an issue, the JVM will probably optimize it enough that the difference between this version and the hypothetical cached version will be negligible. In addition, any performance bottlenecks are much more likely to be in the act of recording the log than in retrieving the logger.

    My advice would be to profile your application to see if it actually make enough of a difference to worry about.