Logging from default interface methods

前端 未结 2 1162
迷失自我
迷失自我 2021-01-01 12:11

Salut to all Java gurus!

Since Java8 we can have default implementations in interfaces (yay!). However problem arises when you want to log from default method.

2条回答
  •  [愿得一人]
    2021-01-01 12:55

    If you don’t want to expose the class LogHolder to the public, don’t make it a member class of the interface. There is no benefit in making it a member class, you don’t even save typing as you have to qualify the field access with the name of the holder class anyway, regardless of whether it is a member class or a class within the same package:

    public interface WithTimeout {
    
        default void onTimeout(Action timedOutAction) {
            LogHolder.LOGGER.info("Action {} time out ignored.", timedOutAction);
        }
    }
    final class LogHolder { // not public
        static final Logger LOGGER = getLogger(WithTimeout.class);
    }
    

提交回复
热议问题