如果 class 有 org 字段,@Slf4j 会生成 non-static variable org cannot be referenced

@Slf4j produces `non-static variable org cannot be referenced` if the class has `org` field

为什么,如果我的 class 有一个 org 字段,我就不能使用 @Slf4j Lombok 日志注释。以下代码将在第 3 行产生编译错误:

MyClass.java:[3,1] non-static variable org cannot be referenced from a static context

import lombok.extern.slf4j.Slf4j;

@Slf4j
class MyClass {
  String org;

  void printDebug() { log.debug("Org: " + org); }
}

Lombok 文档 (projectlombok.org/features/log) 声称它添加了一个 log 字段。为什么它与 org 冲突?

如果您在 IntelliJ 中执行 right-click -> Refactor -> Delombok -> @Log(和朋友),您将看到生成的字段初始化以: = org.slf4j...:

private static final Logger log = org.slf4j.LoggerFactory.getLogger(MyClass.class);
//                                ^^^ - this is ambiguous

这会与您的 org 字段发生冲突:

String org;
//     ^^^

Lombok 团队可以通过注入 import org.slf4j.LoggerFactory 来 work-around,但他们可能认为对修复的需求不是很高。这是 Lombok 贡献者的意见:

...This is a handicap in the java language that uses the same notation for two completely different concepts. Don't know what could be done in lombok to solve this issue without creating some other issue somewhere else. [REF]


解决方案:因此,如果您有 org 字段,只需将 import lombok.extern.slf4j.Slf4j;@Slf4j 替换为:

import static org.slf4j.LoggerFactory.getLogger;



  private static final Logger log = getLogger(MyClass.class);