我正在尝试为我的接口默认方法添加日志记录。例如:
@Slf4j // not allowed
interface MyIFace {
default ThickAndThin doThisAndThat() {
log.error("default doThisAndThat() called");
}
}
问题是我遇到了以下错误:
正确的处理方式是什么?@Slf4j 仅适用于类和枚举。
我正在尝试为我的接口默认方法添加日志记录。例如:
@Slf4j // not allowed
interface MyIFace {
default ThickAndThin doThisAndThat() {
log.error("default doThisAndThat() called");
}
}
正确的处理方式是什么?@Slf4j 仅适用于类和枚举。
因为该注释会生成以下内容,您无法在这里使用Lombok:
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(YourClass.class);
在接口中,您不能使用private关键字。
解决方法是直接编写代码。
interface MyIFace {
org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MyIFace.class);
default ThickAndThin doThisAndThat() {
log.error("default doThisAndThat() called");
}
}
LoggerFactory.getLogger(getClass());
,这将为实际类提供记录器,而不是MyIFace... - Ilario使用Java 9+,您可以使用私有方法来防止日志记录器成为public static。
public interface MyIFace {
private Logger log() {
return LoggerFactory.getLogger(MyIFace.class);
}
default void doThisAndThat() {
log().error("default doThisAndThat() called");
}
}
UnsupportedOperationException("default doThisAndThat()")
而不是记录错误。如果类中未实现该方法并被调用,异常会阻止代码继续执行,而记录日志则会让代码悄悄地继续执行,然后可能有人最终会读取日志并意识到代码存在严重问题。 - Andreas